document.addEventListener("DOMContentLoaded", function () {
  no_scroll();

  // メニューオーバーレイ表示
  $(".menu_btn").click(function () {
    var w = $(this).width();

    $(this).toggleClass("hide");
    $("#overlay_menu .item").toggleClass("hide");
  });

  // ユーザーリストオーバーレイ表示
  $(".user_btn").click(function () {
    var w = $(this).width();

    $(this).toggleClass("hide");
    $("#overlay_user_list.overlay")
      .toggleClass("slidein")
      .css({ transform: "translateX(" & -w & ")" });

    if ($(this).hasClass("hide")) {
      return_scroll();
    } else {
      scrollTo(0, 0);
      no_scroll();
    }
  });

  // モーダルonモーダル（前のモーダルを非表示に）
  // ホスト変更ボタン押下イベント
  $(".ch_host_btn").click(function () {
    var target = $(this).val();
    changeModal(target, "changeHostModal");
  });

  /* モーダルの切り替え */
  function changeModal(beforeModal, afterModal) {
    $(beforeModal).modal("hide");
    $(afterModal).modal("show");
  }

  // 閉じるイベント
  $(".close_btn").click(function () {
    $("#overlay_add_user_list").addClass("none");
    no_scroll();
  });

  // ユーザー追加イベント
  $(".inv_btn").click(function () {
    $("#overlay_add_user_list").addClass("none");
  });

  // ユーザー招待メンバー検索
  $(".add_user_btn").click(function () {
    return_scroll();
    Common.showLoadingIndicator();
    ChatManagementCommon.selectedUserList = [];
    CHAT_UI.refreshMyGroupForAddUserInCollaboration();
    $("#addUserConfirmBtnInCollaboration")
      .off()
      .on("click", function () {
        $("#addUserInCollaboration").modal("hide");
        const selectedUserList =
          ChatManagementCommon.selectedUserList.join(",");
        NativeBridgeDelegate.saveSelectedUserList(selectedUserList);
        CHAT_UI.confirmInviteUserListInCollaboration();
      });
  });
});

function penOff() {
  if (!$("#penBtn .pen").hasClass("disable")) {
    $("#coviewPenCtrBtn").click();
    $("#penBtn .pen").addClass("disable");
  }
}

function no_scroll() {
  document.addEventListener("mousewheel", scroll_control, { passive: false });
  document.addEventListener("touchmove", scroll_control, { passive: false });
}
// スクロール禁止解除
function return_scroll() {
  document.removeEventListener("mousewheel", scroll_control, {
    passive: false,
  });
  document.removeEventListener("touchmove", scroll_control, { passive: false });
}
function scroll_control(event) {
  if (event.cancelable) {
    event.preventDefault();
  }
}

CHAT_UI.confirmInviteUserListInCollaboration = function () {
  var selectedUsers = NativeBridgeDataSource.loadSelectedUsers();
  if (selectedUsers != "") {
    $("#selectedUserListinCollaboration").html("");

    var selectedUserList = NativeBridgeDataSource.loadSelectedUsers();
    selectedUserList.forEach(function (user) {
      user.profileUrl = Common.getProfileImgUrl(user.profileUrl);
    });

    var modalTemplate;
    $.get(
      { url: "./modal_add_user_confirm.html", async: false },
      function (text) {
        modalTemplate = text;
      }
    );
    let html = Mustache.render(modalTemplate, {
      userList: selectedUserList,
    });
    let obj = jQuery.parseHTML(html);
    $("#modal_add_user_confirm").html(obj);
    $("#modalAddUserConfirm").modal("show");
  } else {
  }
  $("#cancelAddUserBtn")
    .off()
    .on("click", function () {
      console.log("cancelClick");
      $("#modalAddUserConfirm").modal("hide");
      $("#addUserInCollaboration").modal("show");
    });

  $("#addUserBtn")
    .off()
    .on("click", function () {
      Common.showLoadingIndicator();
      let userIdList = new Array();
      selectedUserList.forEach(function (user) {
        userIdList.push(user.shopMemberId);
      });
      const commaJoinedUserIDList = userIdList.join(",");
      const collaborationType = CHAT_UTIL.getCollaborationType(
        globalUserInfo.coWorkType
      );

      NativeBridgeDelegate.inviteCollaboration(
        commaJoinedUserIDList,
        collaborationType
      );

      Common.dismissLoadingIndicator();
      $("#modalAddUserConfirm").modal("hide");
    });
};

$("#tabMyGroupOnAddUserInCollaboration").on("click", function (e) {
  CHAT_UI.refreshMyGroupForAddUserInCollaboration();
});

$("#tabAllGroupOnAddUserInCollaboration").on("click", function (e) {
  CHAT_UI.refreshAllGroupForAddUserInCollaboration("0");
});

CHAT_UI.refreshMyGroupForAddUserInCollaboration = function () {
  if (ChatManagementCommon.selectedUserList.length > 0) {
    $(".select_member_num").text(
      ChatManagementCommon.selectedUserList.length
    );
  } else {
    $(".select_member_num").text("0");
  }
  $("#favoriteListForAddUserInCollaboration").html("");
  $("#myGroupListForAddUserInCollaboration").html("");

  $("#tabMyGroupOnAddUserInCollaboration").prop("checked", true);

  // グループの様式を読み込む
  var groupTemplate = getTemplate(
    TemplateURL.ADD_USER_GROUP_LIST_IN_COLLABORATION
  );

  // ユーザの様式を読み込む
  var userTemplate = getTemplate(
    TemplateURL.ADD_USER_USER_LIST_IN_COLLABORATION
  );

  var groupUserTemplate = getTemplate(
    TemplateURL.ADD_USER_GROUP_USER_LIST_IN_COLLABORATION
  );

  NativeBridgeDelegate.updateContactInfo();

  //お気に入りグループ取得。
  var favoriteGroupList = NativeBridgeDataSource.getFavoriteGroups();
  favoriteGroupList.forEach(function (favoriteGroup) {
    let html = Mustache.render(groupTemplate, {
      name: favoriteGroup.groupName,
      id: favoriteGroup.groupId,
    });

    let obj = $(jQuery.parseHTML(html)).on("click", function () {});
    $("#favoriteListForAddUserInCollaboration").append(obj);
  });
  //お気に入りユーザ取得。
  var favoriteUserList = NativeBridgeDataSource.getFavoriteUsersNotInRoom();
  favoriteUserList.forEach(function (favoriteUser) {
    favoriteUser.profileUrl = Common.getProfileImgUrl(favoriteUser.profileUrl);
    let findObj = ChatManagementCommon.selectedUserList.find(function (
      shopMemberId
    ) {
      return shopMemberId == favoriteUser.shopMemberId;
    });
    if (findObj) {
      favoriteUser.checked = "checked";
    }
  });
  let html = Mustache.render(userTemplate, {
    userList: favoriteUserList,
  });
  let obj = jQuery.parseHTML(html);
  $("#favoriteListForAddUserInCollaboration").append(obj);

  var myGroupList = NativeBridgeDataSource.getMyGroupUsersNotInRoom();
  myGroupList.forEach(function (myGroup) {
    myGroup.groupUserList.forEach(function (groupUser) {
      groupUser.profileUrl = Common.getProfileImgUrl(groupUser.profileUrl);
      let findObj = ChatManagementCommon.selectedUserList.find(function (
        shopMemberId
      ) {
        return shopMemberId == groupUser.shopMemberId;
      });
      if (findObj) {
        groupUser.checked = "checked";
      }
    });
    let html = Mustache.render(groupUserTemplate, {
      groupName: myGroup.groupName,
      groupUserList: myGroup.groupUserList,
    });
    let obj = $(jQuery.parseHTML(html)).on("click", function () {});

    $("#myGroupListForAddUserInCollaboration").append(obj);
  });
  $("#addUserInCollaboration").modal("show");
  Common.dismissLoadingIndicator();
};

CHAT_UI.refreshAllGroupForAddUserInCollaboration = function (paramGroupId) {
  var groupId = paramGroupId;
  $(".content").removeClass("none");

  $("#tabAllGroupOnAddUserInCollaboration").prop("checked", true);

  NativeBridgeDelegate.updateGroupInfo(groupId);

  //画面エリアを初期化。
  $("#parentGroupBtnForAddUserInCollaboration").off();
  $("#rootGroupBtnForAddUserInCollaboration").off();
  $("#childGroupListAreaForAddUserInCollaboration").html("");
  $("#userInGroupListForAddUserInCollaboration").html("");
  $("#groupPathAreaForAddUserInCollaboration").html("");

  //DBからグループ情報を取得。
  var result = NativeBridgeDataSource.getGroupInfoForAddUser(groupId);
  //上位グループ、トップグループ遷移ボタンのイベント追加。
  if (typeof result.parentGroupId !== "undefined") {
    $("#parentGroupBtnForAddUserInCollaboration").on("click", function () {
      CHAT_UI.refreshAllGroupForAddUserInCollaboration(result.parentGroupId);
    });
  }
  if (typeof result.rootGroupId !== "undefined") {
    if (paramGroupId == 0) {
      groupId = result.rootGroupId;
    }
    $("#rootGroupBtnForAddUserInCollaboration").on("click", function () {
      CHAT_UI.refreshAllGroupForAddUserInCollaboration(result.rootGroupId);
    });
  }
  if (groupId == result.rootGroupId || paramGroupId == "0") {
    $("#rootGroupAreaInCollaboration").addClass("none");
    $("#parentGroupAreaInCollaboration").addClass("none");
  } else {
    $("#rootGroupAreaInCollaboration").removeClass("none");
    $("#parentGroupAreaInCollaboration").removeClass("none");
  }
  //該当グループのパースを表示。
  var groupPathTemplate = getTemplate(
    TemplateURL.ADD_USER_GROUP_PATH_IN_COLLABORATION
  );

  var groupPathCount = 0;
  result.groupPathList.forEach(function (groupPath) {
    if (!(groupPathCount < result.groupPathList.length - 3)) {
      let html = Mustache.render(groupPathTemplate, {
        name: groupPath.groupName,
        id: groupPath.groupId,
      });
      let obj = jQuery.parseHTML(html);
      $("#groupPathAreaForAddUserInCollaboration").append(obj);
    }
    groupPathCount++;
  });

  //該当グループの下位グループ表示。
  var groupTemplate = getTemplate(
    TemplateURL.ADD_USER_GROUP_LIST_IN_COLLABORATION
  );

  result.childGroupList.forEach(function (childGroup) {
    let html = Mustache.render(groupTemplate, {
      name: childGroup.groupName,
      id: childGroup.groupId,
    });

    let obj = $(jQuery.parseHTML(html)).on("click", function () {});
    $("#childGroupListAreaForAddUserInCollaboration").append(obj);
  });

  //該当グループの所属ユーザを表示。
  var userTemplate = getTemplate(
    TemplateURL.ADD_USER_USER_LIST_IN_COLLABORATION
  );

  result.groupUserList.forEach(function (groupUser) {
    groupUser.profileUrl = Common.getProfileImgUrl(groupUser.profileUrl);
    let findObj = ChatManagementCommon.selectedUserList.find(function (
      shopMemberId
    ) {
      return shopMemberId == groupUser.shopMemberId;
    });
    if (findObj) {
      groupUser.checked = "checked";
    }
  });
  let html = Mustache.render(userTemplate, {
    userList: result.groupUserList,
  });
  let obj = jQuery.parseHTML(html);
  $("#userInGroupListForAddUserInCollaboration").append(obj);
};

CHAT_UI.makeNameCardInCollaboration = function (shopMemberId) {
  if (currentUserInfo.shopMemberId == shopMemberId) {
    return;
  }
  var nameCardInfo = NativeBridgeDataSource.getNameCardData(shopMemberId);
  var namecardTemplate;
  var changeHostTemplate;

  $.get({ url: "./modal_collabo_profile.html", async: false }, function (text) {
    namecardTemplate = text;
  });

  let isCollaborationHost = coview_api.getRoomUsers();
  nameCardInfo.profileUrl = Common.getProfileImgUrl(nameCardInfo.profileUrl);
  let whosHost = $("#collaboration_user_" + nameCardInfo.loginId).hasClass(
    "host"
  );
  let namecardHtml = Mustache.render(namecardTemplate, {
    shopMemberId: nameCardInfo.shopMemberId,
    profileUrl: nameCardInfo.profileUrl,
    loginId: nameCardInfo.loginId,
    name: nameCardInfo.shopMemberName,
    groupPathList: nameCardInfo.groupPathList,
    isFavorite: nameCardInfo.isFavorite,
    isHost: isCollaborationHost,
    whosHost: whosHost,
  });

  let namecardObj = $(jQuery.parseHTML(namecardHtml)).on(
    "click",
    function () {}
  );

  $("#userProfileModalInCollaboration").html(namecardObj);
  $("#userNameCardInCollaboration").modal("show");
};

CHAT_UI.removeFavoriteUserInCollaboration = function (shopMemberId) {
  Common.showLoadingIndicator();
  $("#userNameCardInCollaboration").modal("hide");
  NativeBridgeDataSource.removeFavoriteUser(shopMemberId);
  Common.dismissLoadingIndicator();
};

CHAT_UI.insertFavoriteUserInCollaboration = function (shopMemberId) {
  $("#userNameCardInCollaboration").modal("hide");
  NativeBridgeDataSource.addFavoriteUser(shopMemberId);
  Common.dismissLoadingIndicator();
};

CHAT_UI.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("");

  var joinedUserListTemplate;
  $.get(
    { url: "./collaboration_overlay_user_list.html", async: false },
    function (text) {
      joinedUserListTemplate = text;
    }
  );

  var joinedUserList = NativeBridgeDataSource.getUserListByLoginId(loginIdList);
  var 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();
};

CHAT_UI.toggleCategory = function (category) {
  $(category).toggleClass("open");
  $(category).next().slideToggle();
};

CHAT_UI.refreshForOffline = function () {
  serverInfo.isOnline = "false";
  if (typeof coview_api == "undefined") {
    return;
  }
  const alertString = getLocalizedString("err_weak_network_exit_collaboration");
  alert(alertString);

  NativeBridgeDelegate.finishCollaboration();

  if (collaborationJoinFlg != "2") {
    NativeBridgeDelegate.joinRoom(roomInfo.roomID, roomInfo.name);
  } else {
    NativeBridgeDelegate.openCommunicationHome();
  }
};
