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

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

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

  ChatMakeRoom.bindSearchCancel();
});

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

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

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

    //ユーザデータ検索
    const userList =
      NativeBridgeDataSource.getAllGroupShopMemberByName(keyword);
    ChatMakeRoom.searchUserData(userList);
    const userTemplate = getTemplate(TemplateURL.MAKE_ROOM_USER_LIST);
    const html = ChatMakeRoom.renderUser(userTemplate, userList);
    const obj = jQuery.parseHTML(html);
    overlayMessage.append(obj);

    hasNoData = groupList.length == 0 && userList.length == 0;
  } else {
    // 連絡先画面
    const userList = NativeBridgeDataSource.getMyGroupShopMemberByName(keyword);
    ChatMakeRoom.searchUserData(userList);
    var userTemplate = getTemplate(TemplateURL.MAKE_ROOM_USER_LIST);
    let html = ChatMakeRoom.renderUser(userTemplate, userList);
    let obj = jQuery.parseHTML(html);
    overlayMessage.html(obj);

    hasNoData = userList.length == 0;
  }

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

/** UTIL */

ChatMakeRoom.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) {
    const 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;
    }
    ChatMakeRoom.searchUser(keyword);
    if (enterKeyPressed) {
      searchInput.blur();
      return;
    }
  });
};

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

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

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

ChatMakeRoom.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";
    }
  });
};

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

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

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

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

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

  NativeBridgeDelegate.updateContactInfo();

  ChatMakeRoom.appendFavoriteGroupList();

  ChatMakeRoom.appendFavoriteUserList();

  ChatMakeRoom.appendMyGroupList();
};

ChatMakeRoom.appendFavoriteGroupList = function () {
  // グループの様式を読み込む
  const groupTemplate = getTemplate(TemplateURL.MAKE_ROOM_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);
  });
};

ChatMakeRoom.appendFavoriteUserList = function () {
  // ユーザの様式を読み込む
  const userTemplate = getTemplate(TemplateURL.MAKE_ROOM_USER_LIST);
  const 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);
};

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

ChatMakeRoom.refreshAllGroupForMakeRoom = function (paramGroupId) {
  let 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 () {
      ChatMakeRoom.refreshAllGroupForMakeRoom(result.parentGroupId);
    });
  }
  if (typeof result.rootGroupId !== "undefined") {
    if (paramGroupId == 0) {
      groupId = result.rootGroupId;
    }
    $("#rootGroupBtnForMakeRoom").on("click", function () {
      ChatMakeRoom.refreshAllGroupForMakeRoom(result.rootGroupId);
    });
  }

  if (groupId == result.rootGroupId || paramGroupId == "0") {
    $("#rootGroupArea").addClass("none");
    $("#parentGroupArea").addClass("none");
  } else {
    $("#rootGroupArea").removeClass("none");
    $("#parentGroupArea").removeClass("none");
  }
  //該当グループのパースを表示。
  ChatMakeRoom.appendGroupPathList(result.groupPathList);

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

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

ChatMakeRoom.appendGroupPathList = function (groupPathList) {
  const groupPathTemplate = getTemplate(TemplateURL.MAKE_ROOM_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);
      $("#groupPathAreaForMakeRoom").append(obj);
    }
    groupPathCount++;
  });
};

ChatMakeRoom.appendGroupList = function (childGroupList) {
  const groupTemplate = getTemplate(TemplateURL.MAKE_ROOM_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 () {});
    $("#childGroupListAreaForMakeRoom").append(obj);
  });
};

ChatMakeRoom.appendUsersInGroup = function (groupUserList) {
  var userTemplate = getTemplate(TemplateURL.MAKE_ROOM_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);
  $("#userInGroupListForMakeRoom").append(obj);
};