// 名前空間
var ChatAddUser = {};

document.addEventListener("DOMContentLoaded", function () {
  // メンバー検索
  ChatAddUser.bindMemberSearch();
  // iOSキーボード変換検知用
  ChatAddUser.bindiOSKeyBoardEvent();

  $("#chat_add_user .search_form .cancel").click(function () {
    let roomListTitle = getLocalizedString("inviteUsersSubtitle");
    $("#addUserTitle").text(roomListTitle);
  });
});

// ユーザー検索
ChatAddUser.searchUser = function (keyword) {
  const isAllGroup = $("#tabAllGroupOnAddUser").is(":checked");
  const overlayMessage = $(".overlay_src_msg");
  let hasNoData = false;
  overlayMessage.empty();

  //全グループ検索画面
  if (isAllGroup) {
    //グループデータ検索
    const groupList = NativeBridgeDataSource.getGroupByName(keyword);
    ChatAddUser.searchGroupData(groupList, overlayMessage);

    //ユーザデータ検索
    const userList =
      NativeBridgeDataSource.getAllGroupShopMemberNotInRoomByName(keyword);
    ChatAddUser.searchUserData(userList, overlayMessage);
    hasNoData = userList.length == 0 && groupList.length == 0;

    //連絡先画面
  } else {
    const userList =
      NativeBridgeDataSource.getMyGroupShopMemberNotInRoomByName(keyword);
    searchUserData(userList, overlayMessage);
    hasNoData = userList.length == 0;
  }
  // Set NoResult
  if (hasNoData) {
    const noResultMessage = getNoResultMessage();
    overlayMessage.append(noResultMessage);
  }
};

/** UTILS */

ChatAddUser.bindMemberSearch = function () {
  const searchInput = $('#chat_add_user .search_form input[type="search"]');
  searchInput.click(function (e) {
    //画面タイトル設定
    let contactListTitle = getLocalizedString("userSearch");
    $("#addUserTitle").text(contactListTitle);
  });

  searchInput.keyup(function (e) {
    const keyword = searchInput.val();
    const enterKeyPressed = e.key == "Enter" || e.KeyCode == 13;
    const keywordNotEmpty = keyword != "" && keyword.length != 0;
    const keywordEmpty = keyword == "" || keyword.length < 2;

    if (enterKeyPressed) {
      if (keywordNotEmpty) {
        searchInput.blur();
        return false;
      }
    } else if (keywordEmpty) {
      $(".overlay_src_msg").empty();
      return false;
    }

    ChatAddUser.searchUser(keyword);

    if (enterKeyPressed) {
      searchInput.blur();
      return;
    }
  });
};

ChatAddUser.bindiOSKeyBoardEvent = function () {
  const searchInput = $('#chat_add_user .search_form input[type="search"]');
  searchInput.on("compositionend", function () {
    if (deviceInfo.isiOS()) {
      var keyword = searchInput.val();
      ChatAddUser.searchUser(keyword);
    }
  });
};

ChatAddUser.searchGroupData = function (groupList, overlayMessage) {
  const groupTemplate = getTemplate(TemplateURL.MAKE_ROOM_GROUP_LIST);

  groupList.forEach(function (group) {
    let html = renderGroupTemplate(
      groupTemplate,
      group.groupName,
      group.groupId
    );

    let obj = jQuery.parseHTML(html);
    overlayMessage.append(obj);
  });
};

ChatAddUser.renderGroupTemplate = function (groupTemplate, groupName, groupID) {
  return Mustache.render(groupTemplate, {
    name: groupName,
    id: groupID,
  });
};

ChatAddUser.searchUserData = function (userList, overlayMessage) {
  const userTemplate = getTemplate(TemplateURL.MAKE_ROOM_USER_LIST);
  userList.forEach(function (user) {
    ChatAddUser.setUserProfile(user);
    ChatAddUser.checkUser(user);
  });
  let html = ChatAddUser.renderUserTemplate(userTemplate, userList);
  let obj = jQuery.parseHTML(html);
  overlayMessage.append(obj);
};

ChatAddUser.setUserProfile = function (user) {
  user.profileUrl = Common.getProfileImgUrl(user.profileUrl);
};

ChatAddUser.checkUser = function (user) {
  let findObj = ChatManagementCommon.selectedUserList.find(function (
    shopMemberID
  ) {
    return shopMemberID == user.shopMemberId;
  });
  if (findObj) {
    user.checked = "checked";
  }
};

ChatAddUser.renderUserTemplate = function (userTemplate, userList) {
  return Mustache.render(userTemplate, {
    userList: userList,
  });
};

$("#addUserConfirmBtn").on("click", function (e) {
  const selectedUserList = ChatManagementCommon.selectedUserList.join(",");
  NativeBridgeDelegate.saveSelectedUserList(selectedUserList);
  $("#addUserForm").submit();
});

$("#tabAllGroupOnAddUser").on("click", function (e) {
  ChatAddUser.refreshAllGroupForAddUser("0");
});

$("#tabMyGroupOnAddUser").on("click", function (e) {
  ChatAddUser.refreshMyGroupForAddUser();
});

ChatAddUser.refreshMyGroupForAddUser = function () {
  $(".modal-backdrop").remove();
  $("#favoriteListForMakeRoom").html("");
  $("#myGroupListForMakeRoom").html("");
  //画面タイトル設定
  let contactListTitle = getLocalizedString("userSearch");
  $("#title").text(contactListTitle);

  NativeBridgeDelegate.updateContactInfo();

  // お気に入りグループ表示
  ChatAddUser.appendFavoriteGroup();
  // お気に入りユーザー表示
  ChatAddUser.appendFavoriteUser();
  // マイグループ表示
  ChatAddUser.appendMyGroupList();
};

ChatAddUser.appendFavoriteGroup = function () {
  // グループの様式を読み込む
  const groupTemplate = getTemplate(TemplateURL.ADD_USER_GROUP_LIST);
  // お気に入りグループ取得。
  const 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 () {});
    $("#favoriteListForMakeRoom").append(obj);
  });
};

ChatAddUser.appendFavoriteUser = function () {
  // ユーザの様式を読み込む
  const userTemplate = getTemplate(TemplateURL.ADD_USER_USER_LIST);
  //お気に入りユーザ取得。
  const 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);
  $("#favoriteListForMakeRoom").append(obj);
};

ChatAddUser.appendMyGroupList = function () {
  const groupUserTemplate = getTemplate(TemplateURL.ADD_USER_GROUP_USER_LIST);
  const 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 () {});

    $("#myGroupListForMakeRoom").append(obj);
  });
};

ChatAddUser.refreshAllGroupForAddUser = function (paramGroupId) {
  $(".cancel").addClass("none");
  $(".search_form input").removeClass("focus");
  $(".search_form input").val("");
  $(".search_form form").removeClass();
  $(".content").removeClass("none");
  $(".overlay_src_msg").empty();
  $("#tabAllGroupOnAddUser").prop("checked", true);
  let groupId = paramGroupId;
  //オンライン状態であればサーバから情報更新。
  NativeBridgeDelegate.updateGroupInfo(groupId);

  //画面エリアを初期化。
  ChatAddUser.initialzScreen();

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

  //上位グループ、トップグループ遷移ボタンのイベント追加。
  if (typeof result.parentGroupId !== "undefined") {
    $("#parentGroupBtnForAddUser").on("click", function () {
      ChatAddUser.refreshAllGroupForAddUser(result.parentGroupId);
    });
  }

  if (typeof result.rootGroupId !== "undefined") {
    if (paramGroupId == 0) {
      groupId = result.rootGroupId;
    }
    $("#rootGroupBtnForAddUser").on("click", function () {
      ChatAddUser.refreshAllGroupForAddUser(result.rootGroupId);
    });
  }

  if (groupId == result.rootGroupId || paramGroupId == "0") {
    $("#rootGroupArea").addClass("none");
    $("#parentGroupArea").addClass("none");
  } else {
    $("#rootGroupArea").removeClass("none");
    $("#parentGroupArea").removeClass("none");
  }

  //該当グループのパースを表示。
  ChatAddUser.appendGroupPath(result.groupPathList);

  //該当グループの下位グループ表示。
  ChatAddUser.appendGroupInGroup(result.childGroupList);

  //該当グループの所属ユーザを表示。
  ChatAddUser.appendUserInGroup(result.groupUserList);
};

ChatAddUser.initialzScreen = function () {
  $("#parentGroupBtnForAddUser").off();
  $("#rootGroupBtnForAddUser").off();
  $("#childGroupListAreaForAddUser").html("");
  $("#userInGroupListForAddUser").html("");
  $("#groupPathAreaForAddUser").html("");
};

ChatAddUser.appendGroupPath = function (groupPathList) {
  const groupPathTemplate = getTemplate(TemplateURL.ADD_USER_GROUP_PATH);
  let groupPathCount = 0;
  groupPathList.forEach(function (groupPath) {
    if (!(groupPathCount < groupPathList.length - 3)) {
      let html = Mustache.render(groupPathTemplate, {
        name: groupPath.groupName,
        id: groupPath.groupId,
      });
      let obj = jQuery.parseHTML(html);
      $("#groupPathAreaForAddUser").append(obj);
    }
    groupPathCount++;
  });
};

ChatAddUser.appendGroupInGroup = function (childGroupList) {
  const groupTemplate = getTemplate(TemplateURL.ADD_USER_GROUP_LIST);

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

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

ChatAddUser.appendUserInGroup = function (groupUserList) {
  const userTemplate = getTemplate(TemplateURL.ADD_USER_USER_LIST);
  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: groupUserList,
  });
  let obj = jQuery.parseHTML(html);
  $("#userInGroupListForAddUser").append(obj);
};

ChatAddUser.toggleCategory = function (category) {
  console.log("peacekim:: ChatAddUser.toggleCategory");
  $(category).toggleClass("open");
  $(category).next().slideToggle();
};