// 名前空間
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 = NativeBridgeDataSource.getGroupByName(keyword);
    groupDataSearch(groupList);

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

    hasNoData = userList.length == 0 && groupList.length == 0;
    //連絡先画面
  } else {
    const userList = NativeBridgeDataSource.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 (deviceInfo.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 = Common.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,
  });
};

$("#tabMyGroup").on("click", function (e) {
  $("#contactSearch").attr("placeholder", getLocalizedString("userSearch"));
  CHAT_UI.refreshContactScreen();
});

$("#tabAllGroup").on("click", function (e) {
  CHAT_UI.refreshAllGroupSearch("0");
});

CHAT_UI.refreshContactScreen = function () {
  Common.showLoadingIndicator();
  $("#userNameCard").modal("hide");
  $("#favoriteList").html("");
  $("#myGroupList").html("");
  //画面タイトル設定
  let contactListTitle = getLocalizedString("contactListTitle");
  $("#title").text(contactListTitle);

  // グループの様式を読み込む
  const groupTemplate = getTemplate(TemplateURL.GROUP_LIST);
  // ユーザの様式を読み込む
  var userTemplate = getTemplate(TemplateURL.USER_LIST);

  var myNamecardTemplate = getTemplate(TemplateURL.MY_NAME_CARD);

  var groupUserTemplate = getTemplate(TemplateURL.GROUP_USER_LIST);
  NativeBridgeDelegate.updateContactInfo();

  var myInfo = NativeBridgeDataSource.getMyInfo();
  myInfo.profileImagePath = Common.getProfileImgUrl(myInfo.profileUrl);

  let myNamecardHtml = Mustache.render(myNamecardTemplate, {
    loginId: myInfo.shopMemberId,
    profileImage: myInfo.profileImagePath,
    name: myInfo.shopMemberName,
    groupPathList: myInfo.groupPathList,
  });
  let myNamecardObj = $(jQuery.parseHTML(myNamecardHtml)).on(
    "click",
    function () {}
  );

  $("#myProfileModal").html(myNamecardObj);
  $("#myName").text(myInfo.shopMemberName);
  $("#myImg").attr("src", myInfo.profileImagePath);

  //お気に入りグループ取得。
  var favoriteGroupList = NativeBridgeDataSource.getFavoriteGroups();
  favoriteGroupList.forEach(function (favoriteGroup) {
    let html = Mustache.render(groupTemplate, {
      name: favoriteGroup.groupName,
      id: favoriteGroup.groupId,
      isFavorite: true,
    });

    let obj = $(jQuery.parseHTML(html)).on("click", function () {});
    $("#favoriteList").append(obj);
  });
  //お気に入りユーザ取得。
  var favoriteUserList = NativeBridgeDataSource.getFavoriteUsers();
  favoriteUserList.forEach(function (favoriteUser) {
    favoriteUser.profileUrl = Common.getProfileImgUrl(favoriteUser.profileUrl);
    favoriteUser.isFavorite = true;
  });
  let html = Mustache.render(userTemplate, {
    userList: favoriteUserList,
  });
  let obj = jQuery.parseHTML(html);
  $("#favoriteList").append(obj);

  var myGroupList = NativeBridgeDataSource.getMyGroupUsers();
  myGroupList.forEach(function (myGroup) {
    myGroup.groupUserList.forEach(function (groupUser) {
      groupUser.profileUrl = Common.getProfileImgUrl(groupUser.profileUrl);
    });
    let html = Mustache.render(groupUserTemplate, {
      groupName: myGroup.groupName,
      groupUserList: myGroup.groupUserList,
    });
    let obj = $(jQuery.parseHTML(html)).on("click", function () {});

    $("#myGroupList").append(obj);
  });
  Common.dismissLoadingIndicator();
};

// template_group_list.html (GROUP_LIST)
// >> contact.js
CHAT_UI.favoriteGroupChange = function (groupId, star) {
  if ($(star).hasClass("active")) {
    CHAT_UI.removeFavoriteGroup(groupId);
  } else if ($(star).hasClass("disable")) {
    CHAT_UI.insertFavoriteGroup(groupId);
  }
};

CHAT_UI.removeFavoriteGroup = function (groupId) {
  Common.showLoadingIndicator();
  var result = NativeBridgeDataSource.removeFavoriteGroup(groupId);
  if (result) {
    $(".group_" + groupId).removeClass("active");
    $(".group_" + groupId).addClass("disable");
  } else {
    $(".group_" + groupId).addClass("active");
    $(".group_" + groupId).removeClass("disable");
  }
  Common.dismissLoadingIndicator();
};

CHAT_UI.insertFavoriteGroup = function (groupId) {
  Common.showLoadingIndicator();
  const result = NativeBridgeDataSource.addFavoriteGroup(groupID);
  if (result) {
    $(".group_" + groupId).removeClass("disable");
    $(".group_" + groupId).addClass("active");
  } else {
    $(".group_" + groupId).addClass("disable");
    $(".group_" + groupId).removeClass("active");
  }
  Common.dismissLoadingIndicator();
};