var CoviewBridge = {};
var CollaborationFeature = {};

CoviewBridge.bindReadyEvent = function () {
  coview_api.addEventListener("ready", function () {
    CoviewBridge.bindFermiWebSocketOpenned();

    // add login ID if not exist
    CoviewBridge.addLoginID(globalUserInfo.loginId);
    coview_api.Login(globalUserInfo.loginId);
    CollaborationUI.updateScreen(globalUserInfo.collaborationType);
    NativeBridgeDelegate.setHostRequestFlg(HostRequestFlag.DONE);
  });
};

CoviewBridge.bindFermiWebSocketOpenned = function () {
  try {
    wc_api.addEventListener("open", async function (event) {
      FermiWebSocketMessageHandler.bindWebSocketMessage();
    });
  } catch (err) {
    setTimeout(() => {
      CoviewBridge.bindFermiWebSocketOpenned();
    }, 1000);
  }
};

CoviewBridge.bindStartEvent = function () {
  coview_api.addEventListener("start", function () {
    CollaborationFeature.enableScrollLock();
    CollaborationUI.hideLoadingIndicator();
  });
};

CollaborationFeature.checkAndRetryCamera = async function () {
  if (!deviceInfo.isAndroid) { return; }
  if (globalUserInfo.collaborationType != COLLABORATION_TYPE.VIDEO) { return; }
  if (g_newStream != null) { return; }
  try {
    const cameraStream = await navigator.mediaDevices.getUserMedia(options.constraints);
    if (cameraStream != null && options.isMainMan) {
      ORGcreateLocalVideo(options.constraints);
    } else {
      setTimeout(() => {
        CollaborationFeature.checkAndRetryCamera();
      }, 1000);
    }
  } catch (error) {
    setTimeout(() => {
      CollaborationFeature.checkAndRetryCamera();
    }, 1000);
  }
};

/**************
 * Scroll Lock
 **************/
CollaborationFeature.scrollLock = function (e) {
  if (deviceInfo.isiOS()) {
    if (
      $(e.target).closest(".add_user_modal").length > 0 ||
      $(e.target).closest("#overlay_user_list").length > 0 ||
      $(e.target).closest(".pip_indicator").length > 0
    ) {
      e.stopPropagation();
    } else {
      e.preventDefault();
    }
  }
};

CollaborationFeature.enableScrollLock = function () {
  document
    .getElementById("collabo_main")
    .addEventListener("touchmove", CollaborationFeature.scrollLock, {
      passive: false,
    });
};

CollaborationFeature.disableScrollLock = function () {
  document
    .getElementById("collabo_main")
    .removeEventListener("touchmove", CollaborationFeature.scrollLock, {
      passive: false,
    });
};

CoviewBridge.bindAllByeEvent = function () {
  coview_api.addEventListener("allbye", function () {
    CHAT_SOCKET.emitCollaborationFinishMessage();
    if (deviceInfo.isAndroid()) {
      android.setExitHostAlert();
    }
    if (globalUserInfo.collaborationType == COLLABORATION_TYPE.DOCUMENT) {
      NativeBridgeDelegate.exitMeetingRoom();
    }
    if (globalUserInfo.isInvited()) {
      NativeBridgeDelegate.openCommunicationHome();
    } else {
      NativeBridgeDelegate.joinRoom(roomInfo.roomID, roomInfo.roomName);
    }
    // TODO: peacekim:: check not to need this method for android
    if (deviceInfo.isiOS()) {
      NativeBridgeDelegate.showExitHostAlert();
      return;
    }
    CollaborationUI.hideLoadingIndicator();
  });
};

CoviewBridge.bindGuestByeEvent = function () {
  coview_api.addEventListener("guestbye", function () {
    CollaborationUI.hideLoadingIndicator();
  });
};

CoviewBridge.bindDestroyEvent = function () {
  coview_api.addEventListener("destroy", function () {
    CHAT_SOCKET.emitCollaborationFinishMessage();
    alert(getLocalizedString("inform_exit_host_collaboration"));
    CoviewBridge.exitCollaboration();
    CollaborationUI.hideLoadingIndicator();
  });
};

CoviewBridge.bindMessageEvent = function () {
  coview_api.addEventListener("message", async function (event, json) {
    if (globalUserInfo.isLeaved) {
      return;
    }
    switch (json.api) {
      case "LoginResponse":
        CollaborationFeature.didReceiveLoginResponseMessage();
        break;
      case "CreateRoomResponse":
        if (json.resultCode == 200) {
          CollaborationFeature.didReceiveCreateRoomResponseMessage();
           CollaborationFeature.checkAndRetryCamera();
        }
        break;
      case "joinRoomInfoResponse":
        if (json.resultCode != 200) {
          CollaborationFeature.didReceivedJoinRoomInfoResponseMessage();
        }
        break;
      case "JoinRoomResponse":
        if (json.resultCode != 200) {
          break;
        }
        CollaborationFeature.updateHost();
      // fall through
      case "RoomMemberJoinedEvent":
      // fall through
      case "RoomMemberLeavedEvent":
        attendingUsers = new Array();
        for (let key in g_participants) {
          attendingUsers.push(key);
        }
        CollaborationUI.refreshJoinedCollaboration(attendingUsers);
        break;
      case "HostRequest":
        // to be called by
        // wc_api.dispatchEvent (new Event ("message"), {"HostRequest":"userID"});
        break;
      case "fileChange":
        if (globalUserInfo.collaborationType != COLLABORATION_TYPE.CAMERA) {
          break;
        }
        LoadMobileShareFile(json.fileName);
        backgroundFileName = json.fileName;
        break;
      case "ReceiveMediaResponse":
        if (isBoard && g_isMainMan) {
          wc_api.dispatchEvent(new Event("message"), {
            api: "fileChange",
            fileName: backgroundFileName,
          });
        }
        break;
      case "IceCandidateEvent": // do nothing for ice condidate event
        break;
      case "HeartbeatResponse": // do nothing for heartbeat response
        break;
      default:
        console.debug("Unrecognized api", json);
        break;
    }
  });
};

CollaborationFeature.didReceiveLoginResponseMessage = async function () {
  const isDocument =
    globalUserInfo.collaborationType == COLLABORATION_TYPE.DOCUMENT;
  const isAttendee =
    globalUserInfo.joinType == COLLABORATION_JOIN_TYPE.ATTENDEE;
  const isHost = globalUserInfo.joinType == COLLABORATION_JOIN_TYPE.HOST;

  if (isDocument) {
    if (isAttendee) {
      NativeBridgeDelegate.startContentView();
    } else if (isHost) {
      globalUserInfo.meetingID = NativeBridgeDataSource.createContentView();
      if (globalUserInfo.meetingID == "-1") {
        //会議室作成失敗
        CoviewBridge.finishCollaboration();
        return;
      }
    }
  }

  switch (globalUserInfo.joinType) {
    case COLLABORATION_JOIN_TYPE.INVITED:
    // fall through
    case COLLABORATION_JOIN_TYPE.ATTENDEE:
      // TODO:: here to update host
      coview_api.JoinRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);

      break;
    case COLLABORATION_JOIN_TYPE.HOST:
      let deleteRoomResult = JSON.parse(
        await deleteRoom(globalUserInfo.roomId)
      );
      if (deleteRoomResult.resultCode == 200) {
        waitMillisecond(3000);
      }
      coview_api.CreateRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
      break;
    default:
      break;
  }
  CollaborationFeature.updateHost();
  CollaborationUI.moveToVideoShareArea();
};

CollaborationFeature.didReceiveCreateRoomResponseMessage = function () {
  let coviewInviteMessage =
    "" +
    messageSeperator +
    MessageType.COMMUNICATIONSTART +
    messageSeperator +
    CHAT_UTIL.getCollaborationTypeNumber(globalUserInfo.collaborationType);

  if (globalUserInfo.collaborationType == COLLABORATION_TYPE.DOCUMENT) {
    coviewInviteMessage += messageSeperator + globalUserInfo.meetingID;
  }

  CHAT_SOCKET.emitCreateMessage(coviewInviteMessage, 0);
};

CollaborationFeature.didReceivedJoinRoomInfoResponseMessage = function () {
  alert(getLocalizedString("not_exist_sharing_call"));
  coview_api.LeaveRoom();
  $(".coview_share_area").hide();
  CollaborationUI.hideLoadingIndicator();
  NativeBridgeDelegate.joinRoom(roomInfo.roomID, roomInfo.roomName);
};

CoviewBridge.changeHost = function (userID) {
  // call in agent_app.js
  coview_api.HostChange(userID);
};

CoviewBridge.addLoginID = function (loginID) {
  const url = BIZ_TASK_YELL_URL + "/auth/getuser";
  $.ajax({
    url: url,
    method: "post",
    data: {
      id: loginID,
    },
    success: function (result) {
      if (result.statusCode != 200) {
        coview_api.addUser(loginID);
      }
    },
    error: function (err) {
      console.error(err.toString());
    },
  });
};

CollaborationFeature.updateHost = function () {
  if (g_isMainMan) {
    CollaborationUI.showHostButtons();
  } else {
    CollaborationUI.hideHostButtons();
  }

  CollaborationUI.showHostMark(g_isMainManUsername);

  $("#remoteVideoNameSpan").addClass("hide");
};

CollaborationUI.showHostButtons = function () {

  $(".host_contents").removeClass("none");
  if (globalUserInfo.collaborationType == COLLABORATION_TYPE.CAMERA) {
    $(".photo_select_button").removeClass("none");
  }
  if (globalUserInfo.collaborationType == COLLABORATION_TYPE.VIDEO) {
    $(".video_contents_host").removeClass("none");
    $(".video_contents_user").addClass("none");
  }
};

CollaborationUI.hideHostButtons = function () {

  $(".host_contents").addClass("none");
  if (globalUserInfo.collaborationType == COLLABORATION_TYPE.CAMERA) {
    $(".photo_select_button").addClass("none");
  }
  if (globalUserInfo.collaborationType == COLLABORATION_TYPE.VIDEO) {
    $(".video_contents_user").removeClass("none");
    $(".video_contents_host").addClass("none");
  }
};

CollaborationUI.showHostMark = function (hostName) {
  // remove all host mark
  attendingUsers.forEach(function (userName) {
    const user = "#collaboration_user_" + getReplacedLoginId(userName);
    $(user).removeClass("host");
  })

  // set host name as current user if host name is not set
  if (hostName == "") {
    hostName = getReplacedLoginId(globalUserInfo.loginId);
  }

  // find host named div
  const hostUserDiv = $("#collaboration_user_" + getReplacedLoginId(hostName));

  // add host mark
  if (!hostUserDiv.hasClass("host")) {
    hostUserDiv.addClass("host");
  }
};

function captureAndShareImage(urls, changeHostName) {
  addCaptureEffect();
  $(this).removeClass("on");
  var w, h;
  const video = document.getElementById("localVideo");
  const canvas = document.createElement("canvas");
  if (clientOrientaionState == 1) {
    canvas.width = w = 680;
    canvas.height = h = 515;
  } else {
    canvas.width = w = 386;
    canvas.height = h = 515;
  }
  if (canvas.getContext) {
    const ctx = canvas.getContext("2d");
    ctx.drawImage(video, 0, 0, w, h);
    ctx.drawImage(document.getElementById("canvasRemote"), 0, 0, w, h);
  }

  canvas.toBlob(function (blob) {
    canvasRemote.style.backgroundImage =
      "url('" + URL.createObjectURL(blob) + "')";

    canvasRemote.style.backgroundSize = "contain";

    $(canvasRemote).attr(
      "height",
      $(snapshots[cpatureViewIndex]).attr("height")
    );

    $(canvasRemote).attr("width", $(snapshots[cpatureViewIndex]).attr("width"));

    CollaborationUI.configureCanvasSize($(canvas));

    $(".canvas_wrap").css("background-color", "#000");
    $(".clear_img").show();
    SetShareMenuState("on");
    WithImageShareBtnState("on");

    //Fermi側にイメージ保存。
    let formData = new FormData();
    const uploadFileName =
      "capture_share_" + g_webroom + "_" + g_shareCount + ".png";
    g_shareCount++;
    formData.append("imgFile", blob, uploadFileName);

    $.ajax({
      type: "post",
      url: g_coviewapiserverADDR + "/upload/create",
      data: formData,
      processData: false,
      contentType: false,
      success: function (res) {
        setTimeout(function () {
          SendFileShare(uploadFileName);
          $("#coviewCaptureCtrBtn").hide();
          $("#coviewRecCtrBtn").hide();
          $(".coview_on_media_btn_back").show();
          //アーカイブ保存。
          ArchiveFileManage(blob, uploadFileName, urls);
        }, 1500);
      },
      error: function (err) {
        console.error(err);
      },
    });
  });
}

CollaborationUI.configureCanvasSize = function (canvas) {
  const canvasWrap = $(".canvas_wrap");
  const canvasWidth = $(canvas).attr("width");
  const canvasHeight = $(canvas).attr("height");
  const canvasRatio = canvasWidth / canvasHeight;
  const reversedCanvasRatio = canvasHeight / canvasWidth;
  const canvasWidthValue = canvasWrap.css("width").replace("px", "");
  const canvasHeightValue = canvasWrap.css("height").replace("px", "");
  let h;
  let w;
  if (canvasWidthValue / canvasHeightValue < canvasRatio) {
    h = canvasWidthValue * reversedCanvasRatio;
    w = canvasWidthValue;
  } else {
    h = canvasHeightValue;
    w = canvasHeightValue / reversedCanvasRatio;
  }
  $(canvasRemote).css("height", h);
  $(canvasRemote).css("width", w);
  $(canvasRemote).css("margin-top", -h / 2);
  $(canvasRemote).css("margin-left", -w / 2);
};

function getReplacedLoginId(loginId) {
  return loginId.replaceAll(globalUserInfo.shopName + "_", "");
}

CoviewBridge.exitCollaboration = function () {
  CollaborationFeature.disableScrollLock();
  Common.showLoadingIndicator();

  if (g_isMainMan) {
    CHAT_SOCKET.emitCollaborationFinishMessage();
  }
  if (globalUserInfo.collaborationType == COLLABORATION_TYPE.DOCUMENT) {
    NativeBridgeDelegate.exitMeetingRoom();
  }

  if ($("#recordBtn .record").hasClass("disable")) {
    recordStop(CoviewBridge.finishCollaboration);
  } else {
    CoviewBridge.finishCollaboration();
  }
};

CoviewBridge.finishCollaboration = function () {
  Common.showLoadingIndicator();
  coview_api.LeaveRoom();
  if (coview_api.getRoomUsers()) {
    NativeBridgeDelegate.finishCollaboration();
  }
  globalUserInfo.isLeaved = true;

  if (globalUserInfo.isInvited()) {
    NativeBridgeDelegate.openCommunicationHome();
  } else {
    NativeBridgeDelegate.joinRoom(roomInfo.roomID, roomInfo.roomName);
  }
  Common.dismissLoadingIndicator();
};

// Display User List
CollaborationUI.refreshJoinedCollaboration = function (loginIDList) {
  for (var count = 0; count < loginIDList.length; count++) {
    loginIDList[count] = loginIDList[count].replaceAll(
      globalUserInfo.shopName + "_",
      ""
    );
  }

  $("#collaboration_overlay_user_list").html("");

  const joinedUserListTemplate = getTemplate(
    TemplateURL.COLLABORATION_OVERLAY_USER_LIST
  );

  const joinedUserList =
    NativeBridgeDataSource.getUserListByLoginId(loginIDList);
  const sortedUserList = new Array();

  loginIDList.forEach(function (userID) {
    joinedUserList.forEach(function (user) {
      if (userID == user.loginId) {
        sortedUserList.push(user);
      }
    });
  });

  sortedUserList.forEach(function (user) {
    user.profileUrl = Common.getProfileImgUrl(user.profileUrl);
  });

  let html = Mustache.render(joinedUserListTemplate, {
    joinedUserList: sortedUserList,
  });

  let obj = jQuery.parseHTML(html);
  $("#collaboration_overlay_user_list").append(obj);

  CollaborationFeature.updateHost();
};

CollaborationUI.moveToVideoShareArea = function () {
  CollaborationUI.showLoadingIndicator();
  $(".coview_share_area").show();
  $("#collabo_main").removeClass("none");
};
