var bindOnRefreshGroupList = function () {
  // Update Group List(Invite)
  socket.on(SOCKET_KEY.REFRESH_GROUPLIST, function (groups, isInvite) {
    const groupListElement = $("#group_list");
    groupListElement.html("");
    const template = $("#group-template").html();
    if (groups.length === 0) {
      groupListElement.append(
        '<center class="text-secondary">' +
          getLocalizedString(everyoneIsHere) +
          "</center>"
      );
    }

    addGroupNameAndNumberOfUsers(groups);

    // Rotate
    handleRotate();

    updateTopBar();
    // Set Title
    updateTopBar(isInvite);

    updateUserSelectionLength();

    setupBackButton();
  });
};

var addGroupNameAndNumberOfUsers = function (groups) {
  // グループ名と人数を表記する。
  groups.forEach(function (group) {
    let html = Mustache.render(template, {
      name: group.groupName,
      info: group.memberCnt + getLocalizedString("people"),
    });
    // グループをクリックすると、該当グループのユーザーリストを読み込むようにイベントを与える
    let obj = $(jQuery.parseHTML(html)).on("click", function () {
      // loadingIndicatorを表示
      CHAT_UI.showLoadingIndicator();
      socket.emit("getUserListInGroup", group.groupId, isInvite);
      $("#groupName").text(group.groupName);
    });
    groupListElement.append(obj);
  });
};

var handleRotate = function () {
  if (CHAT_UI.isLandscapeMode()) {
    $(".group_list").addClass("col-6").removeClass("col-12");
  }
};

var setupBackButton = function () {
  const backButton = $("#backButton");

  backButton.show();

  backButton.off().on("click", function () {
    // loadingIndicatorを表示
    CHAT_UI.showLoadingIndicator();
    if (isInvite) {
      $("#pills-chat-tab").tab("show");
    } else {
      if (IS_ONLINE == "true") {
        android.updateRoomList();
        CHAT_UI.refreshRoomList(ChatRoomType.DM);
        CHAT_UI.dismissLoadingIndicator();
      }
    }
  });
};

var updateUserSelectionLength = function () {
  const userSelectionLength = $("#userSelectionLength");
  if (CHAT.globalSelectedUserList.length > 0) {
    userSelectionLength.text(CHAT.globalSelectedUserList.length);
  } else {
    userSelectionLength.text("");
  }
};

var updateTopBar = function (isInvite) {
  // Set Title
  let memberSelectTitle = getLocalizedString("groupSearch");

  $("#pills-group-tab").tab("show");

  const titleRoomName = $(".titleRoomName");
  const userSelectionConfirmButton = $("#userSelectionConfirmBtn");

  titleRoomName.text(memberSelectTitle);
  if (isInvite) {
    $("#newRoomName, .roomListIcon, .chatRoomIcon").hide();
  } else {
    $(".roomListIcon, .chatRoomIcon, #newRoomName").hide();
  }
  userSelectionConfirmButton.show();
  userSelectionConfirmButton.off().on("click", function () {
    CHAT_UI.setConfirmButtonEvent(isInvite);
  });
};
