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

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

  // iOSキーボード変換検知用
  Contact.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);
    Contact.appendGroupList(groupList);

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

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

    hasNoData = userList.length == 0;
  }

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

/** UTILS */

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

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

Contact.appendGroupList = function (groupList) {
  const groupTemplate = getTemplate(TemplateURL.GROUP_LIST);

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

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

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

Contact.appendUserList = function (userList) {
  userList.forEach(function (user) {
    user.profileUrl = Common.getProfileImgUrl(user.profileUrl);
  });
  const userTemplate = getTemplate(TemplateURL.USER_LIST);
  const html = Contact.renderUserList(userTemplate, userList);
  const obj = jQuery.parseHTML(html);
  $(".overlay_src_msg").append(obj);
};

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

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

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

Contact.refreshContactScreen = function () {
  Common.showLoadingIndicator();

  $("#userNameCard").modal("hide");
  $("#favoriteList").html("");
  $("#myGroupList").html("");

  //画面タイトル設定
  let contactListTitle = getLocalizedString("contactListTitle");
  $("#title").text(contactListTitle);

  NativeBridgeDelegate.updateContactInfo();

  Contact.appendMyNamecard();

  Contact.appendFavoritGroupList();

  Contact.appendFavoritUsers();

  Contact.appendMyGroupList();

  Common.dismissLoadingIndicator();
};

Contact.appendMyNamecard = function () {
  const myInfo = NativeBridgeDataSource.getMyInfo();
  myInfo.profileImagePath = Common.getProfileImgUrl(myInfo.profileUrl);

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

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

Contact.appendFavoritGroupList = function () {
  // グループの様式を読み込む
  const groupTemplate = getTemplate(TemplateURL.GROUP_LIST);
  //お気に入りグループ取得。
  const favoriteGroupList = NativeBridgeDataSource.getFavoriteGroups();
  favoriteGroupList.forEach(function (favoriteGroup) {
    const html = Mustache.render(groupTemplate, {
      name: favoriteGroup.groupName,
      id: favoriteGroup.groupId,
      isFavorite: true,
    });

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

Contact.appendFavoritUsers = function () {
  const userTemplate = getTemplate(TemplateURL.USER_LIST);
  const favoriteUserList = NativeBridgeDataSource.getFavoriteUsers();
  favoriteUserList.forEach(function (favoriteUser) {
    favoriteUser.profileUrl = Common.getProfileImgUrl(favoriteUser.profileUrl);
    favoriteUser.isFavorite = true;
  });
  const html = Mustache.render(userTemplate, {
    userList: favoriteUserList,
  });
  const obj = jQuery.parseHTML(html);
  $("#favoriteList").append(obj);
};

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

Contact.favoriteGroupChange = function (groupID, star) {
  if ($(star).hasClass("active")) {
    Contact.removeFavoriteGroup(groupID);
  } else if ($(star).hasClass("disable")) {
    Contact.insertFavoriteGroup(groupID);
  }
};

Contact.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();
};

Contact.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();
};

//全グループ検索画面表示。
Contact.refreshAllGroupSearch = function (paramGroupID) {
  const groupID = paramGroupID;

  Common.showLoadingIndicator();

  Contact.initialzeForAllGroupSearch();

  //オンライン状態であればサーバから情報更新。
  NativeBridgeDelegate.updateGroupInfo(groupID);

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

  Contact.bindGroupCellClick(
    result.parentGroupId,
    result.rootGroupId,
    paramGroupID,
    groupID
  );

  Contact.appendGroupPathList(result.groupPathList);

  Contact.appendSubGroupsInGroup(result.childGroupList);

  Contact.appendUsersInGroup(result.groupUserList);

  Common.dismissLoadingIndicator();
};

Contact.initialzeForAllGroupSearch = function () {
  $("#userNameCard").modal("hide");
  $(".cancel").addClass("none");
  $(".search_form input").removeClass("focus");
  $(".search_form input").val("");
  $(".search_form form").removeClass();
  $(".content").removeClass("none");
  $(".overlay_src_msg").empty();
  $("#contactSearch").attr(
    "placeholder",
    getLocalizedString("searchUserAndGroup")
  );
  $("#tabAllGroup").prop("checked", true);

  //画面エリアを初期化。
  $("#rootGroupBtn").off();
  $("#parentGroupBtn").off();
  $("#childGroupListArea").html("");
  $("#userInGroupList").html("");
  $("#groupPathArea").html("");
};

Contact.bindGroupCellClick = function (
  parentGroupID,
  rootGroupID,
  paramGroupID,
  groupID
) {
  //上位グループ、トップグループ遷移ボタンのイベント追加。
  if (typeof parentGroupID !== "undefined") {
    $("#parentGroupBtn").on("click", function () {
      Contact.refreshAllGroupSearch(parentGroupID);
    });
  }

  if (typeof rootGroupID !== "undefined") {
    if (paramGroupID == 0) {
      groupID = rootGroupID;
    }
    $("#rootGroupBtn").on("click", function () {
      Contact.refreshAllGroupSearch(rootGroupID);
    });
  }

  if (groupID == rootGroupID || paramGroupID == "0") {
    $("#rootGroupArea").addClass("none");
    $("#parentGroupArea").addClass("none");
  } else {
    $("#rootGroupArea").removeClass("none");
    $("#parentGroupArea").removeClass("none");
  }
};

Contact.appendGroupPathList = function (groupPathList) {
  //該当グループのパースを表示。
  const groupPathTemplate = getTemplate(TemplateURL.GROUP_PATH);
  groupPathList.forEach(function (groupPath) {
    let html = Mustache.render(groupPathTemplate, {
      name: groupPath.groupName,
      id: groupPath.groupId,
    });
    let obj = jQuery.parseHTML(html);
    $("#groupPathArea").append(obj);
  });
};

Contact.appendSubGroupsInGroup = function (groupList) {
  //該当グループの下位グループ表示。
  const groupTemplate = getTemplate(TemplateURL.GROUP_LIST);
  groupList.forEach(function (childGroup) {
    const html = Mustache.render(groupTemplate, {
      name: childGroup.groupName,
      id: childGroup.groupId,
      isFavorite: childGroup.isFavorite,
    });

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

Contact.appendUsersInGroup = function (userList) {
  //該当グループの所属ユーザを表示。
  const userTemplate = getTemplate(TemplateURL.USER_LIST);

  userList.forEach(function (user) {
    user.profileUrl = Common.getProfileImgUrl(user.profileUrl);
  });
  const html = Mustache.render(userTemplate, {
    userList: userList,
  });
  const obj = jQuery.parseHTML(html);
  $("#userInGroupList").append(obj);
};