var ChatList = {};

$("#tabDM").on("click", function (e) {
  ChatList.refreshRoomList(ChatRoomType.DM);
});

$("#tabGroup").on("click", function (e) {
  ChatList.refreshRoomList(ChatRoomType.GROUP);
});

document.addEventListener("DOMContentLoaded", function () {
  ChatList.bindChatSearch();
  Common.dismissLoadingIndicator();
});

ChatList.bindChatSearch = function () {
  const chatSearchInput = $('#chat .search_form input[type="search"]');
  const chatSearchCancel = $("#chat .search_form .cancel");
  chatSearchInput.click(function () {
    let roomListTitle = getLocalizedString("room_search_placeholder");
    $("#chatTitle").text(roomListTitle);
  });

  chatSearchCancel.click(function () {
    let roomListTitle = getLocalizedString("roomListTitle");
    $("#chatTitle").text(roomListTitle);
  });

  // チャットメンバー検索
  chatSearchInput.keyup(function (e) {
    var rooms;
    var keyword = chatSearchInput.val();
    const enterKeyPressed = e.KeyCode == 13 || e.key == "Enter";
    if (enterKeyPressed) {
      if (keyword.length != 0 && keyword != "") {
        chatSearchInput.blur();
        return;
      }
    } else if (keyword == "" || keyword.length < 2) {
      $(".overlay_src_msg").empty();
      return;
    }
    ChatList.searchRoom(keyword, rooms);
    if (enterKeyPressed) {
      chatSearchInput.blur();
      return;
    }
  });

  // iOSキーボード変換検知用
  chatSearchInput.on("compositionend", function () {
    if (deviceInfo.isIOS()) {
      var rooms;
      var keyword = chatSearchInput.val();
      ChatList.searchRoom(keyword, rooms);
    }
  });
};

ChatList.refreshRoomList = function (roomType) {
  if (serverInfo.isOnline == true) {
    Common.refreshForOnline();
  } else {
    Common.refreshForOffline();
  }

  const selectedRoomTypeInRoomList = NativeBridgeDataSource.getBeforeRoomType();

  if (selectedRoomTypeInRoomList != null) {
    roomType = selectedRoomTypeInRoomList;
    NativeBridgeDelegate.clearBeforeRoomType();
  }
  Common.showLoadingIndicator();

  // select tab as room type
  ChatList.selectTab(roomType);

  // update room info in native db
  if (serverInfo.isOnline == true) {
    NativeBridgeDelegate.updateRoomList();
  }

  // get room list from native db
  const rooms = NativeBridgeDataSource.getRoomList(roomType, null);

  // Room list 初期化
  ChatList.initializeRoomList();

  // set room title
  ChatList.setRoomTitle();

  // メッセージがない時、最新メッセージにempty messageを追加
  if (rooms.length === 0) {
    ChatList.addEmptyRoomListLabel(roomType);
  }

  // リストにルームを追加
  ChatList.appendRoomList(rooms);

  Common.dismissLoadingIndicator();
};

ChatList.addEmptyRoomListLabel = function (roomType) {
  // 検索結果がない場合のメッセージを追加
  const emptyListString = getLocalizedString("roomListEmptyString");
  switch (roomType) {
    case ChatRoomType.GROUP:
      $("#groupChatList").append(
        `<center class="text-secondary">${emptyListString}</center>`
      );
      break;
    case ChatRoomType.DM:
      $("#dmChatList").append(
        `<center class="text-secondary">${emptyListString}</center>`
      );
      break;
    default:
  }
};

ChatList.selectTab = function (roomType) {
  if (roomType == ChatRoomType.DM) {
    $("#tabDM").prop("checked", true);
  } else {
    $("#tabGroup").prop("checked", true);
  }
};

ChatList.initializeRoomList = function () {
  // #36146に対応
  $("#groupChatList").empty();
  $("#dmChatList").empty();
};

ChatList.setRoomTitle = function () {
  let roomListTitle = getLocalizedString("roomListTitle");
  $("#chatTitle").text(roomListTitle);
};

ChatList.appendRoomList = function (rooms) {
  const template = getTemplate(TemplateURL.ROOM_LIST);

  rooms.forEach(function (room) {
    let html = ChatList.renderRoom(template, room);
    let obj = jQuery.parseHTML(html);
    if (room.type.toString() == ChatRoomType.GROUP) {
      $("#groupChatList").append(obj);
    } else if (room.type.toString() == ChatRoomType.DM) {
      $("#dmChatList").append(obj);
    }
  });
};

ChatList.getDefaultChatRoomName = function (roomAttendUsers) {
  let attendUserName = [];
  roomAttendUsers.forEach(function (user) {
    user.profileUrl = Common.getProfileImgUrl(user.profileUrl);
    attendUserName.push(user.shopMemberName);
  });

  return attendUserName.join(", ");
};

ChatList.getUnreadCount = function (roomUnreadCount) {
  if (roomUnreadCount == 0) {
    return "";
  } else if (roomUnreadCount > 999) {
    return "999+";
  }
  return roomUnreadCount;
};

// チャットルーム検索
ChatList.searchRoom = function (keyword, rooms) {
  const overlayMessage = $(".overlay_src_msg");
  overlayMessage.empty();
  rooms = NativeBridgeDataSource.getRoomList(ChatRoomType.ALL, keyword);
  let roomListTitle = getLocalizedString("room_search_placeholder");
  $("#chatTitle").text(roomListTitle);

  const template = getTemplate(TemplateURL.ROOM_LIST);
  rooms.forEach(function (room) {
    let html = ChatList.renderRoom(template, room);

    // Click event
    let obj = jQuery.parseHTML(html);
    overlayMessage.append(obj);
  });

  if (rooms.length == 0) {
    const noResultMsg = getNoResultMessage();
    overlayMessage.append(noResultMsg);
  }
};

ChatList.getRoomMessage = function (message) {
  if (message) {
    return message.toString();
  } else {
    return getLocalizedString("noMessages");
  }
};

ChatList.getDisplayMessage = function (messageType, roomMessage) {
  switch (messageType) {
    case MessageType.TEXT:
      return roomMessage;
    case MessageType.SYSTEM:
      return roomMessage;
    case MessageType.IMAGE:
      return getLocalizedString("image");
    case MessageType.VIDEO:
      return getLocalizedString("video");
    case MessageType.COMMUNICATIONSTART:
      return getLocalizedString("collaboration_start");
    case MessageType.COMMUNICATIONEND:
      return getLocalizedString("collaboration_end");
    default:
      return roomMessage;
  }
};

ChatList.renderRoom = function (template, room) {
  // thumbnail counts
  const thumbnailCount = Math.min(room.attendUsers.length, 4);

  // set room name
  if (room.chatRoomName == "") {
    room.chatRoomName = ChatList.getDefaultChatRoomName(room.attendUsers);
  }

  // set profile images
  room.profileImagePath = "./images/user-profile.png";
  room.attendUsers.forEach(function (user) {
    user.profileUrl = Common.getProfileImgUrl(user.profileUrl);
  });

  // set room messages
  const roomMessage = ChatList.getRoomMessage(room.message);
  const displayMessage = ChatList.getDisplayMessage(
    room.messageType,
    roomMessage
  );

  // set date string
  const time = room.insertDate
    ? CHAT_UTIL.formatDate(room.insertDate).createdAt
    : "";

  const messageUnreadCount = ChatList.getUnreadCount(room.unreadCount);

  return Mustache.render(template, {
    thumbnailCount: thumbnailCount,
    roomName: room.chatRoomName,
    roomId: room.chatRoomId,
    profileImage: room.profileImagePath,
    lastMessage: displayMessage,
    time: time,
    unreadMsgCnt: messageUnreadCount,
    userCnt: room.attendUsers.length + 1,
    attendUsers: room.attendUsers.splice(0, thumbnailCount),
  });
};

ChatList.refreshForOnline = function () {
  $(".craeteRoomButton").off("click", ChatList.offlineHandler);
  $(".craeteRoomButton").css("opacity", "1.0");
};

ChatList.refreshForOffline = function () {
  $(".craeteRoomButton").on("click", ChatList.offlineHandler);
  $(".craeteRoomButton").css("opacity", "0.3");
};

ChatList.offlineHandler = function (e) {
  e.preventDefault();
};
