/* --------------------------------------------------- */
/* Functions                                           */
/* --------------------------------------------------- */
let coview_api = new CoviewApi();
var isDocument = false;
var isBoard = false;
let isLeaved = false;
let timeInterval = null;
var backgroundFileName;
var isIos;

document.addEventListener("DOMContentLoaded", function () {
  var coviewApiActive = coview_api.Init({
    testSTRParam: "param1",
    testNUMParam: 77,
    testBOOLParam: false,
    coview_api_srv_addr: "https://biztaskyell.abookcloud.com",
    coview_wrap_id: "coviewShare",
    coview_api_key: "8dda7092c5820d663",
  });

  // special button IN Chat ui
  $("#coviewShareMainBtn").on("click", function (e) {
    e.stopPropagation();
    if ($(".coview_share_dropdown_bar").is(":visible") == true) {
      Coview_shareDropdownHide();

      if ($(".coview_share_photo_select_bubble").is(":visible") == true) {
        $(".coview_share_photo_select_bubble").slideUp();
      }
    } else {
      $(".coview_share_dropdown_bar").slideDown();
    }
  });

  $("#coviewShareCloseButton").on("click", function (e) {
    coview_api.LeaveRoom();
    $(".coview_share_area").hide();
  });

  $("body").on("click", function () {
    Coview_shareDropdownHide();

    if ($(".coview_share_photo_select_bubble").is(":visible") == true) {
      $(".coview_share_photo_select_bubble").slideUp();
    } else {
      $(".coview_share_dropdown_bar").slideDown();
    }
  });

  $(document).on("click", ".coview_share_request", function () {
    console.log("globalUserInfo", globalUserInfo);
    if ($(this).hasClass(CollaborationTypeKey.VIDEO) == true) {
      globalUserInfo.coWorkType = CollaborationTypeKey.VIDEO;
      $(".coview_share_title_name").text("LIVE");
    } else if ($(this).hasClass(CollaborationTypeKey.CAMERA) == true) {
      globalUserInfo.coWorkType = CollaborationTypeKey.CAMERA;
      $(".coview_share_title_name").text("ライブラリ");
    } else if ($(this).hasClass(CollaborationTypeKey.AUDIO) == true) {
      globalUserInfo.coWorkType = CollaborationTypeKey.AUDIO;
      $(".coview_share_title_name").text("音声通話");
    }

    coview_api.JoinRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
    Coview_moveToVideoShareArea();
  });

  /* --------------------------------------------------- */
  /* Video, photo, chat, doc                             */
  /* --------------------------------------------------- */
  $("#coviewShareChat").on("click", function () {
    console.log("ON click coviewShareChat");
  });

  $("#coviewSharePhoto").on("click", function (e) {
    e.stopPropagation();
    console.log("ON click coviewSharePhoto");

    if ($(".coview_share_photo_select_bubble").is(":visible") == true) {
      $(".coview_share_photo_select_bubble").slideUp();
    } else {
      $(".coview_share_photo_select_bubble").slideDown();
    }
  });

  $("#coviewSharePhotoCamera").on("click", function () {
    $(".coview_share_photo_select_bubble").hide();
    globalUserInfo.coWorkType = CollaborationTypeKey.CAMERA;
    coview_api.CreateRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
    Coview_moveToVideoShareArea();

    $(".coview_share_title_name").text("カメラ");
  });
  $("#coviewSharePhotoGallery").on("click", function () {
    $(".coview_share_photo_select_bubble").hide();
    globalUserInfo.coWorkType = "gallery";
    coview_api.CreateRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
    Coview_moveToVideoShareArea();

    $(".coview_share_title_name").text("ライブラリ");
  });

  $("#coviewShareAudio").on("click", function () {
    Coview_connect_audio_collaboration();
  });

  $("#coviewShareLive").on("click", function () {
    console.log("ON click coviewShareLive");
    globalUserInfo.coWorkType = "video";
    console.log("globalUserInfo", globalUserInfo);

    coview_api.CreateRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
    Coview_moveToVideoShareArea();

    $(".coview_share_title_name").text("LIVE");
  });

  coview_api.addEventListener("ready", function () {
    console.log("=============> READY : ready for coview api");
    Coview_addLoginId(globalUserInfo.loginId);
    coview_api.Login(globalUserInfo.loginId);
    initCollaborationUI(joinCollaborationType);
    if (CHAT_UTIL.isAndroid()) {
      android.setHostRequestFlg(HostRequestFlag.DONE);
    } else {
      webkit.messageHandlers.setHostRequestFlg.postMessage(
        HostRequestFlag.DONE
      );
    }
    fw.socket.on("message", async function (data) {
      console.log("====> message::data: ", data);
      if (data.type === "CHANGE_COLLABORATION") {
        if (joinCollaborationType == COLLABORATION_TYPE.DOCUMENT) {
          if (CHAT_UTIL.isIOS()) {
            webkit.messageHandlers.exitMeetingRoom.postMessage({});
            webkit.messageHandlers.finishPipMode.postMessage({});
          } else if (CHAT_UTIL.isAndroid()) {
            android.exitMeetingRoom();
            android.finishPip();
            $(".pip_indicator").addClass("none");
          }
          await new Promise(done => setTimeout(() => done(), 500));
          updateCanvasSize();
        }

        if (
          CHAT_UTIL.isAndroid() &&
          data.payload.collaborationType == COLLABORATION_TYPE.DOCUMENT &&
          androidVersion < ANDROID_SDK_VERSION.O
        ) {
          coview_api.HeartBeatUser(globalUserInfo.loginId);
          alert(getLocalizedString("not_support_version"));
          joinCollaborationType = COLLABORATION_TYPE.CAMERA;
        } else {
          joinCollaborationType = data.payload.collaborationType;
        }
        joinMeetingId = data.payload.newMeetingId;
        initCollaborationUI(joinCollaborationType);

        if (CHAT_UTIL.isIOS()) {
          webkit.messageHandlers.joinChangedCollaboration.postMessage({
            joinCollaborationType: joinCollaborationType,
            meetingId: data.payload.newMeetingId,
          });
          if (joinCollaborationType == COLLABORATION_TYPE.DOCUMENT) {
            webkit.messageHandlers.joinMeetingRoom.postMessage(
              data.payload.newMeetingId
            );
          }
        } else if (CHAT_UTIL.isAndroid()) {
          android.joinChangedCollaboration(
            joinCollaborationType,
            data.payload.newMeetingId
          );
          if (joinCollaborationType == COLLABORATION_TYPE.DOCUMENT) {
            android.joinMeetingRoom(data.payload.newMeetingId);
          }
        }
      } else if (data.type === "SHARE_FILE") {
        if (joinCollaborationType != COLLABORATION_TYPE.CAMERA) {
          initCollaborationUI(COLLABORATION_TYPE.CAMERA);
          joinCollaborationType = COLLABORATION_TYPE.CAMERA;
          fw.sendToMsg("others", "SHARE_FILE_HOST", {
            collaborationType: COLLABORATION_TYPE.CAMERA,
          });
        }
      } else if (data.type === "SHARE_FILE_HOST") {
        if (joinCollaborationType != COLLABORATION_TYPE.CAMERA && g_isMainMan) {
          initCollaborationUI(COLLABORATION_TYPE.CAMERA);
          joinCollaborationType = COLLABORATION_TYPE.CAMERA;
        }
      } else if (data.type === "CAPTURE_REQUEST" && g_isMainMan) {
        if (
          confirm(data.payload.name + getLocalizedString("request_capture"))
        ) {
          if ($("#recordBtn .record").hasClass("disable")) {
            screenLock();
            recordStop(function () {
              $("#screenLock").remove();
              captureAndShareImage(
                CMS_SERVER_URL + "/chatapi/file/uploadArchive",
                data.payload.name
              );
            });
          } else {
            captureAndShareImage(
              CMS_SERVER_URL + "/chatapi/file/uploadArchive",
              data.payload.name
            );
          }
        }
      } else if (data.type === "HOST_CHANGE_REQUEST") {
        if (data.payload.loginId == globalUserInfo.loginId) {
          fw.sendToMsg("others", "HOST_CHANGE_RESPONSE", {
            isAndroid: CHAT_UTIL.isAndroid(),
            isAble: androidVersion >= ANDROID_SDK_VERSION.O,
            loginId: CHAT.globalLoginParameter.loginId,
          });
        }
      } else if (data.type === "HOST_CHANGE_RESPONSE") {
        var isAndroid = data.payload.isAndroid;
        var isAble = data.payload.isAble;
        if (
          g_isMainMan &&
          isAndroid &&
          !isAble &&
          joinCollaborationType == COLLABORATION_TYPE.DOCUMENT
        ) {
          coview_api.HeartBeatUser(globalUserInfo.loginId);
          alert(getLocalizedString("err_target_android_version_not_support"));
        } else if (g_isMainMan) {
          fw.sendToMsg("others", "PIP_END_REQUEST", {
            loginId: getFermiLoginId(data.payload.loginId),
          });
          await new Promise(done => setTimeout(() => done(), 500));
          Coview_changeHost(getFermiLoginId(data.payload.loginId));
        }
      } else if (data.type === "PIP_END_REQUEST") {
        if (data.payload.loginId == globalUserInfo.loginId && joinCollaborationType == COLLABORATION_TYPE.DOCUMENT) {
          if (CHAT_UTIL.isAndroid()) {
            android.finishPip();
            $(".pip_indicator").addClass("none");
          } else {
            webkit.messageHandlers.finishPipMode.postMessage({});
          }
        }
      } else if (data.type === "API_SEND_OWNER_CHANGE_COMPLETE") {
        penOff();
        if ($("#recordBtn .record").hasClass("disable")) {
          recordStop(function () {
            console.log("ホスト変更によりレコードを終了しました");
          });
        }
        if ($("#micBtn .voice").hasClass("disable")) {
          micOff();
        } else {
          micOn();
        }
      } else if (data.type === "API_SEND_OWNER_CHANGE_CONFIRM") {
        if (joinCollaborationType == COLLABORATION_TYPE.CAMERA) {
          await new Promise(done => setTimeout(() => done(), 500));
          removeOldLocalVideo(g_localStream);
        }
      } else if (data.type === "CHANGE_HOST_APPLY") {
        if (g_isMainMan) {
          coview_api.HeartBeatUser(globalUserInfo.loginId);
          if (CHAT_UTIL.isAndroid()) {
            $(".pip_indicator").addClass("none");
            android.finishPip();
          } else {
            webkit.messageHandlers.finishPipMode.postMessage({});
          }
        }
        if (CHAT_UTIL.isAndroid()) {
          android.setHostRequestFlg(HostRequestFlag.DOING);
        } else {
          webkit.messageHandlers.setHostRequestFlg.postMessage(
            HostRequestFlag.DOING
          );
        }
        await new Promise(done => setTimeout(() => done(), 500));
        if (g_isMainMan) {
          if (
            confirm(
              getLocalizedString(
                "norify_request_host_change",
                data.payload.hostId
              )
            )
          ) {
            Coview_changeHost(getFermiLoginId(data.payload.hostId));
            if (CHAT_UTIL.isAndroid()) {
              android.setHostRequestFlg(HostRequestFlag.DONE);
            } else {
              webkit.messageHandlers.setHostRequestFlg.postMessage(
                HostRequestFlag.DONE
              );
            }
          } else {
            fw.sendToMsg("others", "HOST_REQUEST_REJECT", {
              hostId: data.payload.hostId,
            });
          }
          fw.sendToMsg("others", "HOST_REQUEST_DONE", {
            hostId: data.payload.hostId,
          });
        }
      } else if (data.type === "HOST_REQUEST_DONE") {
        if (CHAT_UTIL.isAndroid()) {
          android.setHostRequestFlg(HostRequestFlag.DONE);
        } else {
          webkit.messageHandlers.setHostRequestFlg.postMessage(
            HostRequestFlag.DONE
          );
        }
      } else if (data.type === "HOST_REQUEST_REJECT") {
        if (data.payload.hostId == CHAT.globalLoginParameter.loginId) {
          alert("REJECT for owner user");
        }
        if (CHAT_UTIL.isAndroid()) {
          android.setHostRequestFlg(HostRequestFlag.DONE);
        } else {
          webkit.messageHandlers.setHostRequestFlg.postMessage(
            HostRequestFlag.DONE
          );
        }
      } else if (data.type === "GET_COLLABORATION_TYPE" && g_isMainMan) {
        fw.sendToMsg("others", "GET_COLLABORATION_TYPE_RESPONSE", {
          loginId: data.payload.loginId,
          collaborationType: joinCollaborationType,
          newMeetingId: joinMeetingId,
        });
      } else if (data.type === "GET_COLLABORATION_TYPE_RESPONSE") {
        console.log(data.payload.newMeetingId);
        if (data.payload.loginId == globalUserInfo.loginId) {
          if (
            CHAT_UTIL.isAndroid() &&
            data.payload.collaborationType == COLLABORATION_TYPE.DOCUMENT &&
            androidVersion < ANDROID_SDK_VERSION.O
          ) {
            coview_api.HeartBeatUser(globalUserInfo.loginId);
            alert(getLocalizedString("not_support_version"));
            joinCollaborationType = COLLABORATION_TYPE.CAMERA;
          } else {
            joinCollaborationType = data.payload.collaborationType;
          }
          joinMeetingId = data.payload.newMeetingId;
          initCollaborationUI(joinCollaborationType);
          if (CHAT_UTIL.isIOS()) {
            webkit.messageHandlers.joinChangedCollaboration.postMessage({
              joinCollaborationType: joinCollaborationType,
              meetingId: data.payload.newMeetingId,
            });
            if (joinCollaborationType == COLLABORATION_TYPE.DOCUMENT) {
              webkit.messageHandlers.joinMeetingRoom.postMessage(
                data.payload.newMeetingId
              );
            }
          } else if (CHAT_UTIL.isAndroid()) {
            android.joinChangedCollaboration(
              joinCollaborationType,
              data.payload.newMeetingId
            );
            if (joinCollaborationType == COLLABORATION_TYPE.DOCUMENT) {
              android.joinMeetingRoom(data.payload.newMeetingId);
            }
          }
        }
      } else if (data.type === "API_WELCOME") {
        if (collaborationJoinFlg == "2") {
          fw.sendToMsg("others", "GET_COLLABORATION_TYPE", {
            loginId: globalUserInfo.loginId,
          });
          collaborationJoinFlg = "1";
          isInvited = InvitedFlag.INVITED;
        }
      }
    });
  });

  coview_api.addEventListener("start", function () {
    console.log("=============> START : share start");
    scrollLockON();
    $("#loadingIndicator").removeClass("full_active");
  });

  coview_api.addEventListener("allbye", function () {
    requestCollaborationFinish();
    var isDocument = false;
    if (joinCollaborationType == COLLABORATION_TYPE.DOCUMENT) {
      isDocument = true;
    }
    if (CHAT_UTIL.isAndroid()) {
      android.setExitHostAlert();
    }
    if (isDocument) {
      if (CHAT_UTIL.isIOS()) {
        webkit.messageHandlers.exitMeetingRoom.postMessage({});
      } else if (CHAT_UTIL.isAndroid()) {
        android.exitMeetingRoom();
      }
    }
    if (isInvited == InvitedFlag.NONE) {
      CHAT_UI.joinRoom(
        CHAT.globalLoginParameter.roomId,
        CHAT.globalLoginParameter.name
      );
    } else {
      if (typeof android != "undefined") {
        android.openCommunicationHome();
      } else {
        webkit.messageHandlers.openCommunicationHome.postMessage({});
      }
    }
    console.log("=============> HOST BYE : share hostbye");
    if (CHAT_UTIL.isIOS()) {
      webkit.messageHandlers.showExitHostAlert.postMessage({});
      return; 
    }
    $("#loadingIndicator").removeClass("full_active");
  });

  coview_api.addEventListener("guestbye", function () {
    console.log("=============> GUEST BYE : share guestbye");
    $("#loadingIndicator").removeClass("full_active");
  });

  coview_api.addEventListener("destroy", function () {
    requestCollaborationFinish();
    console.log("=============> DESTROY : share destroy");
    alert(getLocalizedString("inform_exit_host_collaboration"));
    var isDocument = false;
    if (joinCollaborationType == COLLABORATION_TYPE.DOCUMENT) {
      isDocument = true;
    }
    Coview_exitCollaboration(isDocument);
    $("#loadingIndicator").removeClass("full_active");
  });

  var meetingId;

  coview_api.addEventListener("message", async function (event, json) {
    console.log("+++ addEventListener", json);
    console.log("processMessage api = ", json.api);
    if (isLeaved) return;
    let loginIdList = new Array();
    switch (json.api) {
      case "LoginResponse":
        if (globalUserInfo.coWorkType == CollaborationTypeKey.DOCUMENT) {
          isDocument = true;
          globalUserInfo.coWorkType = CollaborationTypeKey.AUDIO;
        }
        if (globalUserInfo.coWorkType == CollaborationTypeKey.BOARD) {
          isBoard = true;
          globalUserInfo.coWorkType = CollaborationTypeKey.AUDIO;
        }
        hostSearchInterval();
        if (collaborationJoinFlg == "1") {
          coview_api.JoinRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
          if (isDocument) {
            if (CHAT_UTIL.isIOS()) {
              webkit.messageHandlers.startContentView.postMessage({});
            } else if (CHAT_UTIL.isAndroid()) {
              android.startContentView();
            }
          }
        } else if (collaborationJoinFlg == "0") {
          let deleteRoomResult = JSON.parse(await deleteRoomApi(globalUserInfo.roomId));
          if (deleteRoomResult.resultCode == 200) {
            await new Promise(done => setTimeout(() => done(), 3000));
          }
          coview_api.CreateRoom(
            globalUserInfo.roomId,
            globalUserInfo.coWorkType
          );
          if (isDocument) {
            if (CHAT_UTIL.isIOS()) {
              meetingId = CHAT_DB.createContentView();
            } else if (CHAT_UTIL.isAndroid()) {
              meetingId = android.createContentView();
            }
            joinMeetingId = meetingId;
          }
        } else if (collaborationJoinFlg == "2") {
          isInvited = InvitedFlag.INVITED;
          coview_api.JoinRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
        }
        Coview_moveToVideoShareArea();

        break;
      case "CreateRoomResponse":
        if (json.resultCode == 200) {
          var coviewInviteMessage;
          if (isDocument) {
            coviewInviteMessage =
              "" +
              messageSeperator +
              MessageType.COMMUNICATIONSTART +
              messageSeperator +
              CHAT_UTIL.getCollaborationType(CollaborationTypeKey.DOCUMENT) +
              messageSeperator +
              meetingId;
          } else if (isBoard) {
            coviewInviteMessage =
              "" +
              messageSeperator +
              MessageType.COMMUNICATIONSTART +
              messageSeperator +
              COLLABORATION_TYPE.BOARD;
          } else {
            coviewInviteMessage =
              "" +
              messageSeperator +
              MessageType.COMMUNICATIONSTART +
              messageSeperator +
              CHAT_UTIL.getCollaborationType(globalUserInfo.coWorkType);
          }
          socket.emit(
            "createMessage",
            {
              text: coviewInviteMessage,
            },
            0
          );
        } else {
        }
        break;
      case "joinRoomInfoResponse":
        if (json.resultCode == 200) {
        } else {
          alert(getLocalizedString("not_exist_sharing_call"));
          coview_api.LeaveRoom();
          $(".coview_share_area").hide();
          $("#loadingIndicator").removeClass("full_active");
          CHAT_UI.joinRoom(
            CHAT.globalLoginParameter.roomId,
            CHAT.globalLoginParameter.name
          );
        }
        break;
      case "JoinRoomResponse":
        if (json.resultCode == 200) {
          hostSearchInterval();
          for (let key in g_participants) {
            loginIdList.push(key);
          }
          CHAT_UI.refreshJoinedCollaboration(loginIdList);
        } else {
        }
        break;
      case "RoomMemberJoinedEvent":
        for (let key in g_participants) {
          loginIdList.push(key);
        }
        CHAT_UI.refreshJoinedCollaboration(loginIdList);
        break;
      case "RoomMemberLeavedEvent":
        for (let key in g_participants) {
          loginIdList.push(key);
        }
        CHAT_UI.refreshJoinedCollaboration(loginIdList);
        break;
      case "HostRequest":
        // to be called by
        // wc_api.dispatchEvent (new Event ("message"), {"HostRequest":"userID"});
        console.log("consoleLog", json);
        break;
      case "fileChange":
        if (joinCollaborationType != COLLABORATION_TYPE.CAMERA) {
          break;
        }
        LoadMobileShareFile(json.fileName);
        backgroundFileName = json.fileName;
        console.log("fileChange", json);
        break;
      case "ReceiveMediaResponse":
        if (isBoard && g_isMainMan) {
          wc_api.dispatchEvent(new Event("message"), {
            api: "fileChange",
            fileName: backgroundFileName,
          });
        }
        break;
      default:
        console.log("Unrecognized api", json);
        break;
    }
  });
});

function Coview_shareDropdownHide() {
  $(".coview_share_dropdown_bar").slideUp();
  $(".coview_share_photo_select_bubble").slideUp();
}

function Coview_moveToVideoShareArea() {
  $("#loadingIndicator").addClass("full_active");
  $(".coview_share_area").show();
  $("#collabo_main").removeClass("none");
}

function Coview_moveToAudioShareArea() {
  $(".coview_share_area").addClass("none");
  $("#collabo_main").removeClass("none");
  $(".talking_area").removeClass("none");
}

function changeCollaboration(changeCollaborationType) {
  recordStop(function () {
    var newMeetingId = 0;
      if (joinCollaborationType == COLLABORATION_TYPE.DOCUMENT) {
        if (CHAT_UTIL.isIOS()) {
          webkit.messageHandlers.exitMeetingRoom.postMessage({});
        } else if (CHAT_UTIL.isAndroid()) {
          android.exitMeetingRoom();
        }
      }
      if (CHAT_UTIL.isIOS()) {
        webkit.messageHandlers.setJoinCollaborationType.postMessage(
          changeCollaborationType
        );
      } else if (CHAT_UTIL.isAndroid()) {
        if (
          changeCollaborationType == COLLABORATION_TYPE.DOCUMENT &&
          androidVersion < ANDROID_SDK_VERSION.O
        ) {
          alert(getLocalizedString("not_support_version"));
          return;
        }
        android.setJoinCollaborationType(changeCollaborationType);
      }
      joinCollaborationType = changeCollaborationType;
      initCollaborationUI(changeCollaborationType);
      switch (changeCollaborationType) {
        case COLLABORATION_TYPE.AUDIO:
          coview_api.ChangeCollaboration("audio");
          break;
        case COLLABORATION_TYPE.CAMERA:
          removeOldLocalVideo(g_localStream);
          coview_api.ChangeCollaboration("image");
          break;
        case COLLABORATION_TYPE.VIDEO:
          coview_api.ChangeCollaboration("video");
          break;
        case COLLABORATION_TYPE.DOCUMENT:
          coview_api.ChangeCollaboration("audio");
          if (CHAT_UTIL.isIOS()) {
            newMeetingId = CHAT_DB.createContentView();
          } else if (CHAT_UTIL.isAndroid()) {
            newMeetingId = android.createContentView();
            console.log("newMeetingId = " + newMeetingId);
          }
          break;
        case COLLABORATION_TYPE.BOARD:
          coview_api.ChangeCollaboration("audio");
          break;
      }
      if ($("#micBtn .voice").hasClass("disable")) {
        micOff();
      } else {
        micOn();
      }
      penOff();
      if (CHAT_UTIL.isIOS()) {
        webkit.messageHandlers.changeCollaboration.postMessage({
          changeCollaborationType: changeCollaborationType,
          meetingId: newMeetingId,
        });
      } else if (CHAT_UTIL.isAndroid()) {
        android.changeCollaboration(changeCollaborationType, newMeetingId);
      }
      joinMeetingId = newMeetingId;
      fw.sendToMsg("others", "CHANGE_COLLABORATION", {
        collaborationType: changeCollaborationType,
        newMeetingId: newMeetingId,
      });
  });
}

var scrollLock = function (e) {
  if (CHAT_UTIL.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();
    }
  }
};

let collaboScreen = document.getElementById("collabo_main");

function scrollLockON() {
  collaboScreen.addEventListener("touchmove", scrollLock, { passive: false });
}

function scrollLockOFF() {
  collaboScreen.removeEventListener("touchmove", scrollLock, {
    passive: false,
  });
}

async function initCollaborationUI(changeCollaborationType) {
  $("#coviewEraserCtrBtn").click();
  if ($(".user_btn").hasClass("hide")) {
    $(".user_btn").click();
  }
  if ($(".menu_btn").hasClass("hide")) {
    $(".menu_btn").click();
  }
  if (CHAT_UTIL.isIOS) {
    roomType = CHAT_DB.getRoomType();
    if (roomType == ChatRoomType.DM) {
      $(".add_user_btn").removeClass("none");
    }
  }
  $("link[href='./css/collaboration_board.css']").remove();
  penOff();
  switch (changeCollaborationType) {
    case COLLABORATION_TYPE.AUDIO:
      $(".collaboration_contents").addClass("none");
      $(".voice_contents").removeClass("none");
      break;

    case COLLABORATION_TYPE.CAMERA:
      $(".collaboration_contents").addClass("none");
      $(".picture_contents").removeClass("none");
      break;

    case COLLABORATION_TYPE.VIDEO:
      $(".collaboration_contents").addClass("none");
      $(".video_contents").removeClass("none");
      break;

    case COLLABORATION_TYPE.DOCUMENT:
      $(".collaboration_contents").addClass("none");
      $(".document_contents").removeClass("none");
      break;

    case COLLABORATION_TYPE.BOARD:
      $(".collaboration_contents").addClass("none");
      $(".board_contents").removeClass("none");
      $("head").append(
        '<link rel="stylesheet" href="./css/collaboration_board.css">'
      );
      break;
  }
  await waitMillisecond(1000);
  $(".before_loading_indicator").addClass("none");
}

function Coview_exitCollaboration(isDocument = false) {
  scrollLockOFF();
  if (g_isMainMan) {
    requestCollaborationFinish();
  }
  if (isDocument) {
    if (CHAT_UTIL.isIOS()) {
      webkit.messageHandlers.exitMeetingRoom.postMessage({});
    } else if (CHAT_UTIL.isAndroid()) {
      android.exitMeetingRoom();
    }
  }
  if ($("#recordBtn .record").hasClass("disable")) {
    recordStop(Coview_finishCollaboration);
  } else {
    Coview_finishCollaboration();
  }
}

function Coview_finishCollaboration() {
  clearInterval(timeInterval);
  coview_api.LeaveRoom();
  if (coview_api.getRoomUsers()) {
    if (CHAT_UTIL.isIOS()) {
      webkit.messageHandlers.finishCollaboration.postMessage({});
    } else if (CHAT_UTIL.isAndroid()) {
      android.finishCollaboration();
    }
  }
  isLeaved = true;
  if (isInvited == InvitedFlag.NONE) {
    CHAT_UI.joinRoom(
      CHAT.globalLoginParameter.roomId,
      CHAT.globalLoginParameter.name
    );
  } else {
    if (typeof android != "undefined") {
      android.openCommunicationHome();
    } else {
      webkit.messageHandlers.openCommunicationHome.postMessage({});
    }
  }
}

function Coview_changeHost(userId) {
  console.log("Change Host To " + userId);
  changeOwnerSend(userId);
}

function Coview_addLoginId(loginId) {
  console.log("addUser loginId = " + loginId);
  var url = "https://biztaskyell.abookcloud.com/auth/getuser";
  $.ajax({
    url: url,
    method: "post",
    data: {
      id: loginId,
    },
    success: function (result) {
      console.log("result", result);
      if (result.statusCode != 200) {
        coview_api.addUser(loginId);
      }
    },
    error: function (err) {
      console.log(err.toString());
    },
  });
}

function applyForHostChange() {
  if (
    joinCollaborationType == COLLABORATION_TYPE.DOCUMENT &&
    androidVersion < ANDROID_SDK_VERSION.O &&
    CHAT_UTIL.isAndroid()
  ) {
    alert(getLocalizedString("not_support_version"));
    return;
  }
  var hostRequestFlg = 0;
  if (CHAT_UTIL.isAndroid()) {
    hostRequestFlg = android.getHostRequestFlg();
  } else {
    hostRequestFlg = CHAT_DB.getHostRequestFlg();
  }
  if (hostRequestFlg == HostRequestFlag.DOING) {
    alert(getLocalizedString("already_processing_host_request"));
    return;
  }
  if (CHAT_UTIL.isAndroid()) {
    android.setHostRequestFlg(HostRequestFlag.DOING);
  } else {
    webkit.messageHandlers.setHostRequestFlg.postMessage(HostRequestFlag.DOING);
  }
  fw.sendToMsg("others", "CHANGE_HOST_APPLY", {
    hostId: CHAT.globalLoginParameter.loginId,
  });
}

function Coview_connect_audio_collaboration() {
  globalUserInfo.coWorkType = CollaborationTypeKey.AUDIO;
  coview_api.deleteRoom(globalUserInfo.roomId);
  coview_api.CreateRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
  Coview_moveToVideoShareArea();
  Coview_moveToAudioShareArea();
  $(".coview_share_title_name").text("音声通話");
}

function hostSearchInterval() {
  let hostName = "";
  function hostSearch() {
    if (g_isMainMan) {
      $("#collaboration_user_" + CHAT.globalLoginParameter.loginId).addClass(
        "host"
      );
      $(".host_contents").removeClass("none");
      if (joinCollaborationType == COLLABORATION_TYPE.CAMERA) {
        $(".photo_select_button").removeClass("none");
      }
      if (joinCollaborationType == COLLABORATION_TYPE.VIDEO) {
        $(".video_contents_host").removeClass("none");
        $(".video_contents_user").addClass("none");
      }
      if (CHAT_UTIL.isIOS()) isIos = true;
    } else {
      $("#collaboration_user_" + CHAT.globalLoginParameter.loginId).removeClass(
        "host"
      );
      $(".host_contents").addClass("none");
      if (joinCollaborationType == COLLABORATION_TYPE.CAMERA) {
        $(".photo_select_button").addClass("none");
      }
      if (joinCollaborationType == COLLABORATION_TYPE.VIDEO) {
        $(".video_contents_user").removeClass("none");
        $(".video_contents_host").addClass("none");
      }
    }
    if (hostName != g_isMainManUsername) {
      if (hostName != "") {
        $("#collaboration_user_" + getReplacedLoginId(hostName)).removeClass(
          "host"
        );
      }
      $(
        "#collaboration_user_" + getReplacedLoginId(g_isMainManUsername)
      ).addClass("host");
      hostName = g_isMainManUsername;
    } else {
      if (hostName == "") {
        if (
          !$(
            "#collaboration_user_" + CHAT.globalLoginParameter.loginId
          ).hasClass("host") &&
          coview_api.getRoomUsers()
        ) {
          $(
            "#collaboration_user_" + CHAT.globalLoginParameter.loginId
          ).addClass("host");
        }
      } else {
        if (
          !$("#collaboration_user_" + getReplacedLoginId(hostName)).hasClass(
            "host"
          )
        ) {
          $("#collaboration_user_" + getReplacedLoginId(hostName)).addClass(
            "host"
          );
        }
      }
    }
  }
  timeInterval = setInterval(hostSearch, 2000);
}

function hostChangeRequest(loginId) {
  fw.sendToMsg("others", "HOST_CHANGE_REQUEST", {
    loginId: getFermiLoginId(loginId),
  });
}

function getFermiLoginId(loginId) {
  return globalUserInfo.shopName + "_" + loginId;
}

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

function captureAndShareImage(urls, changeHostName) {
  addCaptureEffect();
  $(this).removeClass("on");
  var w, h;
  var video = document.getElementById("localVideo");
  var 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) {
    var ctx = canvas.getContext("2d");
    ctx.drawImage(video, 0, 0, w, h);
    ctx.drawImage(document.getElementById("canvasRemote"), 0, 0, w, h);
  }
  canvas.toBlob(function (blob) {
    var newImg = document.createElement("img");
    var url = URL.createObjectURL(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"));
    console.log("url", URL.createObjectURL(blob));
    if (
      $(".canvas_wrap").css("width").replace("px", "") /
        $(".canvas_wrap").css("height").replace("px", "") <
      $(canvas).attr("width") / $(canvas).attr("height")
    ) {
      var h =
        $(".canvas_wrap").css("width").replace("px", "") *
        ($(canvas).attr("height") / $(canvas).attr("width"));
      var w = $(".canvas_wrap").css("width").replace("px", "");
      $(canvasRemote).css("height", h);
      $(canvasRemote).css("width", w);
      $(canvasRemote).css("margin-top", -h / 2);
      $(canvasRemote).css("margin-left", -w / 2);
    } else {
      var h = $(".canvas_wrap").css("height").replace("px", "");
      var w =
        $(".canvas_wrap").css("height").replace("px", "") /
        ($(canvas).attr("height") / $(canvas).attr("width"));
      $(canvasRemote).css("height", h);
      $(canvasRemote).css("width", w);
      $(canvasRemote).css("margin-top", -h / 2);
      $(canvasRemote).css("margin-left", -w / 2);
    }
    $(".canvas_wrap").css("background-color", "#000");
    $(".clear_img").show();
    SetShareMenuState("on");
    WithImageShareBtnState("on");

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

    var uploadUrl =
      location.protocol +
      "//" +
      location.hostname +
      ":" +
      location.port +
      "/upload/create";
    if (!location.port) {
      uploadUrl =
        location.protocol + "//" + location.hostname + "/upload/create";
    }
    $.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_share_title_name").text("LIVE(CAPTURE IMAGE)");
          $(".coview_on_media_btn_back").show();
          //アーカイブ保存。
          ArchiveFileManage(blob, uploadFileName, urls);
        }, 1500);
      },
      error: function (err) {
        console.log(err);
      },
    });
  });
}

function toolToggle(){
  if($("#collabo_footer_menu").hasClass('hide')){
    $("#collabo_footer_menu").removeClass('hide');
  }else{
    $("#collabo_footer_menu").addClass('hide');
  }
}

function micOn() {
  coview_api.MicMuteControl("off");
  $("#micBtn .voice").removeClass("disable");
}

function micOff() {
  coview_api.MicMuteControl("on");
  $("#micBtn .voice").addClass("disable");
}

function micTogle() {
  if ($("#micBtn .voice").hasClass("disable")) {
    micOn();
  } else {
    micOff();
  }
}

function recordStart() {
  console.log("レコードを開始しました");
  MainManRecord("on");
  $("#recordBtn .record").addClass("disable");
  $('.flash-txt').addClass('on');
}

function recordFinished() {
  $("#recordBtn .record").removeClass("disable");
  $('.flash-txt').removeClass('on');
  // ロック画面の削除
  delete_dom_obj("screenLock");
}

function recordTogle() {
  if (!$("#recordBtn .record").hasClass("disable")) {
    recordStart();
  } else {
    recordStop(function () {
      console.log("レコードを終了しました");
    });
  }
}

function recordStop(callback) {
  if (!$("#recordBtn .record").hasClass("disable")) {
    callback();
    return;
  }
  CHAT_UI.showLoadingIndicator();
  // アーカイブ保存中は画面操作不可(協業終了,協業切り替え防止)
  screenLock();

  // アーカイブ保存処理
  MainManRecordWithCollaboration(
    "stop",
    CMS_SERVER_URL + "/chatapi/file/uploadArchive",
    callback
  );
}

function MainManRecordWithCollaboration(action, url, callback) {
  try {
    mediaRecorder.stop();
  } catch(exeption) {
    console.log("Record fail");
    callback();
  }
  console.log("Recorded Blobs: ", recordedBlobs);

  setTimeout(function () {
    console.log("Recoding File upload..");
    const blob = new Blob(recordedBlobs, { type: "video/webm" });
    console.log(blob);
    var uploadFileName = "record_" + g_webroom + "_" + g_shareCount + ".webm";
    g_shareCount++;
    var formData = new FormData();
    formData.append("fileData", blob, uploadFileName);
    formData.append("sid", globalUserInfo.sid);
    formData.append("roomId", globalUserInfo.roomId);
    if (joinCollaborationType == COLLABORATION_TYPE.VIDEO) {
      formData.append("archiveType", 1);
    } else {
      formData.append("archiveType", 2);
    }
    console.log(uploadFileName);
    $.ajax({
      type: "post",
      url,
      data: formData,
      contentType: false,
      processData: false,
      success: function (res) {
        recordFinished();
        CHAT_UI.dismissLoadingIndicator();
        console.log(res);
        callback();
      },
      error: function (err) {
        recordFinished();
        CHAT_UI.dismissLoadingIndicator();
        console.log(err);
        callback();
      },
    });
  }, 1000);
}

function screenLock() {
  // ロック用のdivを生成
  var element = document.createElement("div");
  element.id = "screenLock";

  // ロック用のスタイル
  element.style.height = "100%";
  element.style.left = "0px";
  element.style.position = "fixed";
  element.style.top = "0px";
  element.style.width = "100%";
  element.style.zIndex = "9999";
  element.style.opacity = "0";

  var objBody = document.getElementsByTagName("body").item(0);
  objBody.appendChild(element);
}

// div削除関数
function delete_dom_obj(id_name) {
  var dom_obj = document.getElementById(id_name);
  var dom_obj_parent = dom_obj.parentNode;
  dom_obj_parent.removeChild(dom_obj);
}

function requestCollaborationFinish() {
  if (socket != null && socket.connected) {
    socket.emit(
      "createMessage",
      {
        text: DATA_MESSAGE_SCHEME + FINISH_ALL_COLLABORATION_SIGNAL,
      },
      0
    );
  }
}

async function waitMillisecond(millesecond) {
  await new Promise(done => setTimeout(() => done(), millesecond));
}

function penToggle() {
  $("#coviewPenCtrBtn").click();
  if ($("#penBtn .pen").hasClass("disable")) {
    $("#penBtn .pen").removeClass("disable");
  } else {
    $("#penBtn .pen").addClass("disable");
  }
}
function photo_open_place_holderToggle() {
  $("#open_file_upload").trigger("click");
}
function eraserToggle() {
  $("#coviewEraserCtrBtn").click();
}
function captureToggle() {
  if ($("#recordBtn").hasClass("bg_red")) {
    screenLock();
    recordStop(function () {
      $("#screenLock").remove();
      coview_api.Capture(CMS_SERVER_URL + "/chatapi/file/uploadArchive");
    });
  } else {
    coview_api.Capture(CMS_SERVER_URL + "/chatapi/file/uploadArchive");
  }
}
function captureRequestToggle() {
  fw.sendToMsg("others", "CAPTURE_REQUEST", {
    name: CHAT.globalLoginParameter.loginId,
  });
}