var ChatManagementCommon = {};

//招待するメンバーを保存する変数
ChatManagementCommon.selectedUserList = new Array();

ChatManagementCommon.showMakeRoomConfirmView = function () {
  $("#selectedUserList").html("");

  var userTemplate = getTemplate(TemplateURL.MAKE_ROOM_CONFIRM_USER_LIST);

  var selectedUserList = NativeBridgeDataSource.loadSelectedUsers();

  selectedUserList.forEach(function (user) {
    let html = Mustache.render(userTemplate, {
      id: user.shopMemberId,
      profileImage: Common.getProfileImgUrl(user.profileUrl),
      name: user.shopMemberName,
    });
    let obj = jQuery.parseHTML(html);
    $("#selectedUserList").append(obj);
  });

  $("#makeRoomBtn")
    .off()
    .on("click", function () {
      // #36130に対応
      const trimmedRoomName = $("#newRoomName").val().trim();
      if (trimmedRoomName.length == 0) {
        // loadingIndicatorを表示
        Common.showLoadingIndicator();
        let userIdList = new Array();
        let userNameList = new Array();

        selectedUserList.forEach(function (user) {
          userIdList.push(user.shopMemberId);
          userNameList.push(user.shopMemberName);
        });

        // 参加ユーザ名でルーム名を生成
        let newRoomName =
          currentUserInfo.loginId + "," + userNameList.join(",");
        NativeBridgeDelegate.createChatRoom(
          ChatRoomType.DM,
          userIdList.join(","),
          newRoomName,
          MakeRoomFlag.MAKE_ROOM,
          false
        );
      } else if (
        trimmedRoomName.includes(";") ||
        trimmedRoomName.includes("/") ||
        trimmedRoomName.includes("?") ||
        trimmedRoomName.includes(":") ||
        trimmedRoomName.includes("@") ||
        trimmedRoomName.includes("&") ||
        trimmedRoomName.includes("=") ||
        trimmedRoomName.includes("+") ||
        trimmedRoomName.includes("$") ||
        trimmedRoomName.includes(",") ||
        trimmedRoomName.includes("-") ||
        trimmedRoomName.includes("_") ||
        trimmedRoomName.includes(".") ||
        trimmedRoomName.includes("!") ||
        trimmedRoomName.includes("~") ||
        trimmedRoomName.includes("*") ||
        trimmedRoomName.includes("'") ||
        trimmedRoomName.includes("(") ||
        trimmedRoomName.includes(")") ||
        trimmedRoomName.includes("#") ||
        trimmedRoomName.includes("\\") ||
        trimmedRoomName.includes('"') ||
        trimmedRoomName.includes("`")
      ) {
        // #36147
        // #36174
        $("#customAlertTitle").text(getLocalizedString("invalidCharacter"));
        $("#customAlertOk").text(getLocalizedString("yesTitle"));

        $("#customAlert")
          .appendTo("body")
          .modal({
            backdrop: "static",
            keyboard: false,
          })
          .on("click", "#customAlertOk", function (e) {});
      } else if (trimmedRoomName.length > 20) {
        // #36142
        var inputText = $("#newRoomName").val().trim(); // #36142 文字列の前又は後の空白文字列を削除

        // #36174
        $("#customAlertTitle").text(getLocalizedString("nameTooLong"));
        $("#customAlertOk").text(getLocalizedString("yesTitle"));

        $("#customAlert")
          .appendTo("body")
          .modal({
            backdrop: "static",
            keyboard: false,
          })
          .on("click", "#customAlertOk", function (e) {
            $("#newRoomName").val(
              inputText.substr(0, $("#newRoomName").prop("maxlength"))
            );
          });
      } else {
        //loadingIndicatorを表示
        Common.showLoadingIndicator();
        let userIdList = new Array();

        selectedUserList.forEach(function (user) {
          userIdList.push(user.shopMemberId);
        });

        // TODO: check why here using trimmedroomname instead of encodedRoomName
        // ルーム名のtrimmingした後、URIencodingを行う
        const encodedRoomName = encodeURIComponent(trimmedRoomName);
        NativeBridgeDelegate.createChatRoom(
          ChatRoomType.DM,
          userIdList.join(","),
          trimmedRoomName,
          MakeRoomFlag.MAKE_ROOM,
          false
        );
      }
    });

  $("#newRoomName").attr("placeholder", getLocalizedString("newRoomName"));
};

ChatManagementCommon.showAddUserConfirmView = function () {
  $("#selectedUserList").html("");

  var userTemplate = getTemplate(TemplateURL.ADD_USER_CONFIRM_USER_LIST);
  var selectedUserList = NativeBridgeDataSource.loadSelectedUsers();

  selectedUserList.forEach(function (user) {
    let html = Mustache.render(userTemplate, {
      id: user.shopMemberId,
      profileImage: Common.getProfileImgUrl(user.profileUrl),
      name: user.shopMemberName,
    });
    let obj = jQuery.parseHTML(html);
    $("#selectedUserList").append(obj);
  });

  $("#addUserBtn")
    .off()
    .on("click", function () {
      Common.showLoadingIndicator();
      let userIdList = new Array();
      selectedUserList.forEach(function (user) {
        userIdList.push(user.shopMemberId);
      });
      NativeBridgeDelegate.inviteUsers(userIdList.join(","));
    });
};

ChatManagementCommon.refreshAllGroupForMakeRoom = function (paramGroupId) {
  var groupId = paramGroupId;
  $(".cancel").addClass("none");
  $(".search_form input").removeClass("focus");
  $(".search_form input").val("");
  $(".search_form form").removeClass();
  $(".content").removeClass("none");
  $(".overlay_src_msg").empty();

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

  //オンライン状態であればサーバから情報更新。
  NativeBridgeDelegate.updateGroupInfo(groupId);

  //画面エリアを初期化。
  $("#parentGroupBtnForMakeRoom").off();
  $("#rootGroupBtnForMakeRoom").off();
  $("#childGroupListAreaForMakeRoom").html("");
  $("#userInGroupListForMakeRoom").html("");
  $("#groupPathAreaForMakeRoom").html("");

  //DBからグループ情報を取得。
  var result = NativeBridgeDataSource.getGroupInfo(groupId);

  //上位グループ、トップグループ遷移ボタンのイベント追加。
  if (typeof result.parentGroupId !== "undefined") {
    $("#parentGroupBtnForMakeRoom").on("click", function () {
      ChatManagementCommon.refreshAllGroupForMakeRoom(result.parentGroupId);
    });
  }
  if (typeof result.rootGroupId !== "undefined") {
    if (paramGroupId == 0) {
      groupId = result.rootGroupId;
    }
    $("#rootGroupBtnForMakeRoom").on("click", function () {
      CHAChatManagementCommon_UI.refreshAllGroupForMakeRoom(result.rootGroupId);
    });
  }
  if (groupId == result.rootGroupId || paramGroupId == "0") {
    $("#rootGroupArea").addClass("none");
    $("#parentGroupArea").addClass("none");
  } else {
    $("#rootGroupArea").removeClass("none");
    $("#parentGroupArea").removeClass("none");
  }
  //該当グループのパースを表示。
  var groupPathTemplate = getTemplate(TemplateURL.MAKE_ROOM_GROUP_PATH);

  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);
      $("#groupPathAreaForMakeRoom").append(obj);
    }
    groupPathCount++;
  });

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

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

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

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

  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);
  $("#userInGroupListForMakeRoom").append(obj);
};

ChatManagementCommon.checkForMakeChat = function (checkMemberId) {
  let findObj = ChatManagementCommon.selectedUserList.find(function (
    shopMemberId
  ) {
    return shopMemberId == checkMemberId;
  });
  if (findObj) {
    // remove
    ChatManagementCommon.selectedUserList =
      ChatManagementCommon.selectedUserList.filter(function (
        shopMemberId
      ) {
        return checkMemberId != shopMemberId;
      });
    $(".checkbox" + checkMemberId)
      .prop("checked", false)
      .trigger("change");
  } else {
    // add
    ChatManagementCommon.selectedUserList.push(checkMemberId);
    $(".checkbox" + checkMemberId)
      .prop("checked", true)
      .trigger("change");
  }

  let cnt = ChatManagementCommon.selectedUserList.length;
  if (ChatManagementCommon.selectedUserList.length > 0) {
    $(".select_member_num").text(cnt);
  } else {
    $(".select_member_num").text("0");
  }
};
