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

CoviewBridge.bindReadyEvent = function () {
  coview_api.addEventListener("ready", function () {
    CoviewBridge.addLoginId(globalUserInfo.loginId);
    coview_api.Login(globalUserInfo.loginId);
    updateCollaborationUI(joinCollaborationType);
    NativeBridgeDelegate.setHostRequestFlg(HostRequestFlag.DONE);
    FermiWebSocketMessageHandler.bindWebSocketMessage();
  });
};

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

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 (joinCollaborationType == COLLABORATION_TYPE.DOCUMENT) {
      NativeBridgeDelegate.exitMeetingRoom();
    }
    if (isInvited == InvitedFlag.NONE) {
      NativeBridgeDelegate.joinRoom(roomInfo.roomID, roomInfo.roomName);
    } else {
      NativeBridgeDelegate.openCommunicationHome();
    }
    // 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"));
    Coview_exitCollaboration();
    CollaborationUI.hideLoadingIndicator();
  });
};

CoviewBridge.bindMessageEvent = function () {
  let meetingId;
  coview_api.addEventListener("message", async function (event, json) {
    console.log("peacekim:: +++ addEventListener", json);
    console.log("peacekim:: 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) {
            NativeBridgeDelegate.startContentView();
          }
        } else if (collaborationJoinFlg == "0") {
          let deleteRoomResult = JSON.parse(
            await deleteRoomApi(globalUserInfo.roomId)
          );
          if (deleteRoomResult.resultCode == 200) {
            waitMillisecond(3000);
          }
          coview_api.CreateRoom(
            globalUserInfo.roomId,
            globalUserInfo.coWorkType
          );
          if (isDocument) {
            meetingId = NativeBridgeDataSource.createContentView();
            joinMeetingId = meetingId;
          }
        } else if (collaborationJoinFlg == "2") {
          isInvited = InvitedFlag.INVITED;
          coview_api.JoinRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
        }
        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);
          }
          CHAT_SOCKET.emitCreateMessage(coviewInviteMessage, 0);
        }
        break;
      case "joinRoomInfoResponse":
        if (json.resultCode == 200) {
        } else {
          alert(getLocalizedString("not_exist_sharing_call"));
          coview_api.LeaveRoom();
          $(".coview_share_area").hide();
          CollaborationUI.hideLoadingIndicator();
          NativeBridgeDelegate.joinRoom(roomInfo.roomID, roomInfo.roomName);
        }
        break;
      case "JoinRoomResponse":
        if (json.resultCode == 200) {
          hostSearchInterval();
          for (let key in g_participants) {
            loginIdList.push(key);
          }
          CollaborationUI.refreshJoinedCollaboration(loginIdList);
        } else {
        }
        break;
      case "RoomMemberJoinedEvent":
        for (let key in g_participants) {
          loginIdList.push(key);
        }
        CollaborationUI.refreshJoinedCollaboration(loginIdList);
        break;
      case "RoomMemberLeavedEvent":
        for (let key in g_participants) {
          loginIdList.push(key);
        }
        CollaborationUI.refreshJoinedCollaboration(loginIdList);
        break;
      case "HostRequest":
        // to be called by
        // wc_api.dispatchEvent (new Event ("message"), {"HostRequest":"userID"});
        console.log("peacekim:: t2 consoleLog", json);
        break;
      case "fileChange":
        if (joinCollaborationType != COLLABORATION_TYPE.CAMERA) {
          break;
        }
        LoadMobileShareFile(json.fileName);
        backgroundFileName = json.fileName;
        console.log("peacekim:: fileChange", json);
        break;
      case "ReceiveMediaResponse":
        if (isBoard && g_isMainMan) {
          wc_api.dispatchEvent(new Event("message"), {
            api: "fileChange",
            fileName: backgroundFileName,
          });
        }
        break;
      default:
        console.log("peacekim:: Unrecognized api", json);
        break;
    }
  });
};

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

CoviewBridge.addLoginId = function (loginID) {
  const url = "https://biztaskyell.abookcloud.com/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());
    },
  });
};

function hostSearchInterval() {
  let hostName = "";
  function hostSearch() {
    if (g_isMainMan) {
      $("#collaboration_user_" + currentUserInfo.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 (deviceInfo.isiOS()) isIos = true;
    } else {
      $("#collaboration_user_" + currentUserInfo.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_" + currentUserInfo.loginID).hasClass(
            "host"
          ) &&
          coview_api.getRoomUsers()
        ) {
          $("#collaboration_user_" + currentUserInfo.loginID).addClass("host");
        }
      } else {
        if (
          !$("#collaboration_user_" + getReplacedLoginId(hostName)).hasClass(
            "host"
          )
        ) {
          $("#collaboration_user_" + getReplacedLoginId(hostName)).addClass(
            "host"
          );
        }
      }
    }
  }
  timeInterval = setInterval(hostSearch, 2000);
}

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) {
    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("peacekim:: t5 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_on_media_btn_back").show();
          //アーカイブ保存。
          ArchiveFileManage(blob, uploadFileName, urls);
        }, 1500);
      },
      error: function (err) {
        console.log(err);
      },
    });
  });
}

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

function Coview_exitCollaboration() {
  CollaborationFeature.disableScrollLock();
  if (g_isMainMan) {
    CHAT_SOCKET.emitCollaborationFinishMessage();
  }
  if (joinCollaborationType == COLLABORATION_TYPE.DOCUMENT) {
    NativeBridgeDelegate.exitMeetingRoom();
  }
  if ($("#recordBtn .record").hasClass("disable")) {
    recordStop(Coview_finishCollaboration);
  } else {
    Coview_finishCollaboration();
  }
}

function Coview_finishCollaboration() {
  clearInterval(timeInterval);
  coview_api.LeaveRoom();
  NativeBridgeDelegate.finishCollaboration(true);
  if (coview_api.getRoomUsers()) {
    NativeBridgeDelegate.finishCollaboration();
  }
  isLeaved = true;
  if (isInvited == InvitedFlag.NONE) {
    NativeBridgeDelegate.joinRoom(roomInfo.roomID, roomInfo.roomName);
  } else {
    NativeBridgeDelegate.openCommunicationHome();
  }
}

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

  Common.showLoadingIndicator();
  $("#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);

  Common.dismissLoadingIndicator();
};

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