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

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

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

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

  //全グループ検索画面
  if (isAllGroup) {
    //グループデータ検索
    const groupList = CHAT_DB.getGroupByName(keyword);
    groupDataSearch(groupList);

    //ユーザデータ検索
    const userList = CHAT_DB.getAllGroupShopMemberByName(keyword);
    userDataSearch(userList);

    hasNoData = userList.length == 0 && groupList.length == 0;
    //連絡先画面
  } else {
    const userList = CHAT_DB.getMyGroupShopMemberByName(keyword);
    userDataSearch(userList);

    hasNoData = userList.length == 0;
  }

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

/** UTILS */

var bindiOSKeyBoardEvent = function () {
  const searchInput = $('#contact .search_form input[type="search"]');
  searchInput.on("compositionend", function () {
    if (CHAT_UTIL.isIOS()) {
      var keyword = searchInput.val();
      CONTACT.searchUser(keyword);
    }
  });
};

var bindMemeberSearch = function () {
  const searchInput = $('#contact .search_form input[type="search"]');
  searchInput.keyup(function (e) {
    const keyword = searchInput.val();
    const enterKeyPressed = e.key == "Enter" || e.KeyCode == 13;
    const keywordEmpty = keyword == "" || keyword.length < 2;
    const keywordNotEmpty = keyword != "" && keyword.length != 0;

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

var groupDataSearch = function (groupList) {
  const groupTemplate = getTemplate(TemplateURL.GROUP_LIST);

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

    let obj = jQuery.parseHTML(html);
    $(".overlay_src_msg").append(obj);
  });
};

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

var userDataSearch = function (userList) {
  userList.forEach(function (user) {
    user.profileUrl = CHAT.getProfileImgUrl(user.profileUrl);
  });
  var userTemplate = getTemplate(TemplateURL.USER_LIST);
  let html = renderUserList(userTemplate, userList);
  let obj = jQuery.parseHTML(html);
  $(".overlay_src_msg").append(obj);
};

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