var ChatList = {};

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

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

document.addEventListener("DOMContentLoaded", 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();
    if (e.KeyCode == 13 || e.key == "Enter") {
      if (keyword.length != 0 && keyword != "") {
        chatSearchInput.blur();
        return;
      }
    } else if (keyword == "" || keyword.length < 2) {
      $(".overlay_src_msg").empty();
      return;
    }
    CHAT.searchRoom(keyword, rooms);
    if (e.KeyCode == 13 || e.key == "Enter") {
      chatSearchInput.blur();
      return;
    }
  });
  // iOSキーボード変換検知用
  chatSearchInput.on(
    "compositionend",
    function () {
      if (deviceInfo.isIOS()) {
        var rooms;
        var keyword = chatSearchInput.val();
        CHAT.searchRoom(keyword, rooms);
      }
    }
  );
});

ChatList.refreshRoomList = function (roomType) {
  if (serverInfo.isOnline == "true") {
    Common.refreshForOnline();
  } else {
    Common.refreshForOffline();
  }
  const beforeRoomType = NativeBridgeDataSource.getBeforeRoomType();

  if (beforeRoomType != null) {
    roomType = beforeRoomType;
    NativeBridgeDelegate.clearBeforeRoomType();
  }
  Common.showLoadingIndicator();
  if (roomType == ChatRoomType.DM) {
    $("#tabDM").prop("checked", true);
  } else {
    $("#tabGroup").prop("checked", true);
  }

  if (serverInfo.isOnline == "true") {
    NativeBridgeDelegate.updateRoomList();
  }
  var rooms = NativeBridgeDataSource.getRoomList(roomType, null);
  // #36146に対応
  $("#groupChatList").empty();
  $("#dmChatList").empty();
  let roomListTitle = getLocalizedString("roomListTitle");
  $("#chatTitle").text(roomListTitle);
  if (rooms.length === 0) {
    // 検索結果がない場合のメッセージを追加
    let 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:
    }
  }

  var template = getTemplate(TemplateURL.ROOM_LIST);

  rooms.forEach(function (room) {
    room.profileImagePath = "./images/user-profile.png";
    if (room.message) {
      room.message = room.message.toString();
    } else {
      room.message = getLocalizedString("noMessages");
    }
    var displayMsg;
    //TODO 協業の場合処理追加必要
    switch (room.messageType) {
      case MessageType.TEXT:
        displayMsg = room.message;
        break;
      case MessageType.IMAGE:
        displayMsg = getLocalizedString("image");
        break;
      case MessageType.VIDEO:
        displayMsg = getLocalizedString("video");
        break;
      case MessageType.COMMUNICATIONSTART:
        displayMsg = getLocalizedString("collaboration_start");
        break;
      case MessageType.COMMUNICATIONEND:
        displayMsg = getLocalizedString("collaboration_end");
        break;
      default:
        break;
    }
    var attendUserName = [];

    room.attendUsers.forEach(function (user) {
      user.profileUrl = Common.getProfileImgUrl(user.profileUrl);
      attendUserName.push(user.shopMemberName);
    });
    var thumbnailCount =
      room.attendUsers.length > 4 ? 4 : room.attendUsers.length;
    if (room.chatRoomName == "") {
      room.chatRoomName = attendUserName.join(", ");
    }
    var unreadMessageCount = room.unreadCount == 0 ? "" : room.unreadCount;
    if (unreadMessageCount > 999) {
      unreadMessageCount = "999+";
    }
    let html = Mustache.render(template, {
      thumbnailCount: thumbnailCount,
      roomName: room.chatRoomName,
      roomId: room.chatRoomId,
      profileImage: room.profileImagePath,
      lastMessage: displayMsg,
      time: room.insertDate
        ? CHAT_UTIL.formatDate(room.insertDate).createdAt
        : "",
      unreadMsgCnt: unreadMessageCount,
      userCnt: room.attendUsers.length + 1,
      attendUsers: room.attendUsers,
    });
    // Click event
    let obj = $(jQuery.parseHTML(html)).on("click", function () {
      //TODO ルームに入る処理追加必要
    });
    // ルームグループごとに追加。
    switch (roomType) {
      case ChatRoomType.GROUP:
        $("#groupChatList").append(obj);
        break;
      case ChatRoomType.DM:
        $("#dmChatList").append(obj);
        break;
      default:
    }
  });

  console.log("DONE");
  Common.dismissLoadingIndicator();
};

// チャットルーム検索
CHAT.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);

  var template = getTemplate(TemplateURL.ROOM_LIST);
  rooms.forEach(function (room) {
    room.profileImagePath = "./images/user-profile.png";
    const roomMessage = getRoomMessage(room.message);
    const displayMessage = getDisplayMessage(room.messageType, roomMessage);

    let html = renderRoom(template, room, displayMessage);

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

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

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

var 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 "";
  }
};

var renderRoom = function (template, room, displayMessage) {
  var attendUserName = [];
  room.attendUsers.forEach(function (user) {
    user.profileUrl = Common.getProfileImgUrl(user.profileUrl);
    attendUserName.push(user.shopMemberName);
  });
  const thumbnailCount =
    room.attendUsers.length > 4 ? 4 : room.attendUsers.length;
  const time = room.insertDate
    ? CHAT_UTIL.formatDate(room.insertDate).createdAt
    : "";
  if (room.chatRoomName == "") {
    room.chatRoomName = attendUserName.join(", ");
  }
  return Mustache.render(template, {
    thumbnailCount: thumbnailCount,
    roomName: room.chatRoomName,
    roomId: room.chatRoomId,
    profileImage: room.profileImagePath,
    lastMessage: displayMessage,
    time: time,
    unreadMsgCnt: room.unreadCount == 0 ? "" : room.unreadCount,
    userCnt: room.attendUsers.length + 1,
    attendUsers: room.attendUsers,
  });
};

CHAT_UI.refreshForOnline = function () { 
  serverInfo.isOnline = "true";
  $(".craeteRoomButton").off("click", CHAT_UI.offlineHandler);
  $(".craeteRoomButton").css("opacity", "1.0");
};

CHAT_UI.refreshForOffline = function () {
  serverInfo.isOnline = "false";
  $(".craeteRoomButton").on("click", CHAT_UI.offlineHandler);
  $(".craeteRoomButton").css("opacity", "0.3");
}

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