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

document.addEventListener("DOMContentLoaded", function () {
  // メンバー検索
  searchMember();

  // iOSキーボード変換検知用
  bindiOSKeyBoardEvent();

  bindSearchCancel();
});

// メンバー検索
CHAT_MAKE_ROOM.searchUser = function (keyword) {
  const overlayMessage = $(".overlay_src_msg");
  const isAllGroup = $("#tabAllGroupOnMakeRoom").is(":checked");
  let hasNoData = false;
  overlayMessage.empty();

  //全グループ検索画面
  if (isAllGroup) {
    //グループデータ検索
    var groupList = NativeBridgeDataSource.getGroupByName(keyword);
    var groupTemplate = getTemplate(TemplateURL.MAKE_ROOM_GROUP_LIST);

    groupList.forEach(function (group) {
      let html = renderRoomList(groupTemplate, group.groupName, group.groupId);
      let obj = jQuery.parseHTML(html);
      overlayMessage.append(obj);
    });

    //ユーザデータ検索
    var userList = NativeBridgeDataSource.getAllGroupShopMemberByName(keyword);
    searchUserData(userList);
    var userTemplate = getTemplate(TemplateURL.MAKE_ROOM_USER_LIST);
    let html = renderUser(userTemplate, userList);
    let obj = jQuery.parseHTML(html);
    overlayMessage.append(obj);
    hasNoData = groupList.length == 0 && userList.length == 0;
    //連絡先画面
  } else {
    const userList = NativeBridgeDataSource.getMyGroupShopMemberByName(keyword);
    searchUserData(userList);
    var userTemplate = getTemplate(TemplateURL.MAKE_ROOM_USER_LIST);
    let html = renderUser(userTemplate, userList);
    let obj = jQuery.parseHTML(html);
    overlayMessage.html(obj);

    hasNoData = userList.length == 0;
  }

  if (hasNoData) {
    const noResultMsg = getNoResultMessage();
    overlayMessage.append(noResultMsg);
  }
};

/** UTIL */

var searchMember = function () {
  const searchInput = $('#chatMakeRoom .search_form input[type="search"]');
  searchInput.click(function (e) {
    let contactListTitle = getLocalizedString("userSearch");
    $("#makeRoomTitle").text(contactListTitle);
  });
  searchInput.keyup(function (e) {
    var keyword = searchInput.val();
    const enterKeyPressed = e.KeyCode == 13 || e.key == "Enter";
    const keywordEmpty = keyword == "" || keyword.length < 2;
    const keywordNotEmpty = keyword != "" && keyword.length != 0;
    //画面タイトル設定
    if (enterKeyPressed) {
      if (keywordNotEmpty) {
        searchInput.blur();
        return false;
      }
    } else if (keywordEmpty) {
      $(".overlay_src_msg").empty();
      return false;
    }
    CHAT_MAKE_ROOM.searchUser(keyword);
    if (enterKeyPressed) {
      searchInput.blur();
      return;
    }
  });
};

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

var bindSearchCancel = function () {
  $("#chatMakeRoom .search_form .cancel").click(function () {
    let roomListTitle = getLocalizedString("createRoomTitle");
    $("#makeRoomTitle").text(roomListTitle);
  });
};

var renderRoomList = function (url, groupName, groupID) {
  return Mustache.render(url, {
    name: groupName,
    id: groupID,
  });
};

var searchUserData = function (userList) {
  userList.forEach(function (user) {
    user.profileUrl = Common.getProfileImgUrl(user.profileUrl);
    let findObj = ChatManagementCommon.selectedUserList.find(function (
      shopMemberId
    ) {
      return shopMemberId == user.shopMemberId;
    });
    if (findObj) {
      user.checked = "checked";
    }
  });
};

var renderUser = function (url, userList) {
  return Mustache.render(url, {
    userList: userList,
  });
};

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

$("#tabAllGroupOnMakeRoom").on("click", function (e) {
  ChatManagementCommon.refreshAllGroupForMakeRoom("0");
});

$("#tabMyGroupOnMakeRoom").on("click", function (e) {
  CHAT_UI.refreshMyGroupForMakeRoom();
});

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

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

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

  var groupUserTemplate = getTemplate(TemplateURL.MAKE_ROOM_GROUP_USER_LIST);

  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 () {});
    $("#favoriteListForMakeRoom").append(obj);
  });
  //お気に入りユーザ取得。
  var favoriteUserList = NativeBridgeDataSource.getFavoriteUsers();
  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);

  var myGroupList = NativeBridgeDataSource.getMyGroupUsers();
  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);
  });
};
