const userMessageTemplate = getTemplate(TemplateURL.USER_MESSAGE);
const myMessageTemplate = getTemplate(TemplateURL.MY_MESSAGE);
const systemMessageTemplate = getTemplate(TemplateURL.SYSTEM_MESSAGE);
const collaborationMessageTemplate = getTemplate(
  TemplateURL.OPEN_COLLABORATION_MESSAGE
);
/***********************
 *  Search Messages
 ***********************/
ChatRoom.appendSearchMessages = function (messages, unwrappedWorkVal = "") {
  console.log("peacekim:: ChatRoom.appendSearchMessages mesage: " + messages);
  let workVal = unwrappedWorkVal;
  messages.forEach(function (message) {
    let html = ChatRoom.renderMessageForSearchMessage(message);
    workVal = html + workVal;
  });
  $(".overlay_src_msg").append(workVal);
};

ChatRoom.renderMessageForSearchMessage = function (message) {
  console.log(
    "peacekim:: ChatRoom.renderMessageForSearchMessage mesage: " + messages
  );
  let template = ChatRoom.getChatMessageTemplate(
    message.messageType,
    message.shopMemberId
  );

  let messageTime = CHAT_UTIL.formatDate(message.insertDate);

  message.profileUrl = ChatRoom.parseUserProfileURL(message.profileUrl);

  message.message = message.message
    .toString()
    .replaceAll("?fileName=", "?sid=" + currentUserInfo.sid + "&fileName=");

  let html = Mustache.render(template, {
    text: message.message,
    from: message.loginId,
    shopMemberId: message.shopMemberId,
    profileImage: message.profileUrl,
    createdAtDay: messageTime.createdAtDay,
    createdAtTime: messageTime.createdAtTime,
  });

  return message.message.includes("attachedImages") ||
    message.message.includes("attachedVideos")
    ? CHAT_UTIL.htmlDecode(html)
    : html;
};

/***********************
 *  Send Messages
 ***********************/
// Input recognize
$("#messageInput").on("keypress", function (event) {
  console.log("peacekim:: ChatRoom - messageInput keypressed");
  if (event.which == 13) {
    // Enterキーの処理
    $("#messageSend").click();
  }
});

ChatRoom.sendMessage = function (e) {
  console.log("peacekim:: ChatRoom - sendMessage");
  const messageTextBox = $("#messageInput");
  const message =
    messageTextBox.val().length > 0
      ? encodeURIComponent(messageTextBox.val())
      : "";
  messageTextBox.val("");

  if (message.length > 0) {
    const sendData = message + messageSeperator + MessageType.TEXT;
    CHAT_SOCKET.emitCreateMessage(sendData, 0);
  }
  $(".message_input_form").focus();
};

/***********************
 *  Load Messages
 ***********************/
ChatRoom.loadMessages = function (joinRoomID, joinRoomName) {
  console.log(
    "peacekim:: ChatRoom.loadMessages joinRoomID: " +
      joinRoomID +
      ", joinRoomName: " +
      joinRoomName
  );
  let roomID = joinRoomID.toString().replace(/['"]+/g, "");
  roomName = joinRoomName;
  // 画面更新
  if (serverInfo.isOnline == true) {
    Common.refreshForOnline();
    NativeBridgeDelegate.updateMessages(roomID);
  } else {
    Common.refreshForOffline();
  }

  // setup ルームタイトル
  $("#roomTitle").text(roomName).data("roomName", roomName);

  // ルームメニュー表示設定
  ChatRoom.configureRoomMenu();

  // ユーザー表示
  ChatRoom.appendAttendedUsers(roomID);

  // メッセージ表示
  let messages = NativeBridgeDataSource.getMessagesByRoomID(roomID);
  ChatRoom.prependMessage(messages);

  window.addEventListener(
    "load",
    function (event) {
      ChatRoom.scrollToBottom(false);
    },
    false
  );
};

ChatRoom.configureRoomMenu = function () {
  console.log("peacekim:: ChatRoom.configureRoomMenu");
  if (roomInfo.roomType == ChatRoomType.DM) {
    $("#roomMenu").removeClass("none");
  } else {
    $("#roomMenu").addClass("none");
  }
};

ChatRoom.appendAttendedUsers = function (roomID) {
  console.log("peacekim:: ChatRoom.appendAttendedUsers roomID: " + roomID);
  const topUserListTemplate = getTemplate(TemplateURL.CHATROOM_USER_LIST);
  const filterUserListTemplate = getTemplate(
    TemplateURL.CHATROOM_USER_FILTER_LIST
  );

  const users = NativeBridgeDataSource.getUsersInRoom(roomID);

  // ユーザーリスト表示
  users.forEach(function (user) {
    user.profileUrl = Common.getProfileImgUrl(user.profileUrl);
  });
  let html = Mustache.render(topUserListTemplate, {
    userList: users,
  });
  let obj = jQuery.parseHTML(html);
  $("#user_list").append(obj);

  // フィルタリングユーザーリスト表示
  let filterHtml = Mustache.render(filterUserListTemplate, {
    userList: users,
  });
  let filterObj = jQuery.parseHTML(filterHtml);
  $("#filter").append(filterObj);
};

ChatRoom.prependMessage = function (messages) {
  console.log(
    "peacekim:: ChatRoom.appendAttendedUsers prependMessage: " + messages
  );
  const now = new Date();

  const messageElement = $("#messages");
  let checkBeforeDate = "";
  let beforeDate = "";
  messages.forEach(function (message) {
    // プロフィールURL設定
    message.profileUrl = ChatRoom.parseUserProfileURL(message.profileUrl);

    const messageCreatedTime = CHAT_UTIL.formatDate(
      message.insertDate
    ).createdAt;

    // #36147
    message.message = message.message
      .toString()
      .replaceAll("?fileName=", "?sid=" + currentUserInfo.sid + "&fileName=");

    // 日付表示のため、今年なのか、本日なのかを判定
    const isOtherYear = now.getFullYear() != message.insertDate.substring(0, 4);
    const isToday = messageCreatedTime.includes(":") ? true : false;

    // 日付ラーベル表示
    if (
      messageCreatedTime != checkBeforeDate &&
      checkBeforeDate != "" &&
      !isToday
    ) {
      const html = ChatRoom.renderDateLabelMessage(beforeDate);
      messageElement.append(html);
    }

    checkBeforeDate = messageCreatedTime;
    beforeDate = message.insertDate;

    const html = ChatRoom.renderMessage(message, isToday, isOtherYear);
    messageElement.append(html);
  });

  // messageが存在する場合、最上段にそのメッセージの日付を表示
  ChatRoom.appendInitialDateMessage(messages);
};

ChatRoom.appendInitialDateMessage = function (messages) {
  console.log(
    "peacekim:: ChatRoom.appendAttendedUsers appendInitialDateMessage: " +
      messages
  );
  if ($(".chat_message").length != 0 && messages.length != 0) {
    $("#initial-date-message").detach();
    const html = ChatRoom.renderDateLabelMessage(
      messages[messages.length - 1].insertDate,
      true
    );
    $("#messages").append(html);
  }
};

ChatRoom.renderDateLabelMessage = function (
  beforeDate,
  isInitialDateMessage = false
) {
  let messageDay = CHAT_UTIL.systemDay(beforeDate);
  return Mustache.render(systemMessageTemplate, {
    year: messageDay.year + getLocalizedString("year"),
    month: messageDay.month + getLocalizedString("month"),
    day: messageDay.day + getLocalizedString("day"),
    dow: CHAT_UTIL.findDow(messageDay.dow),
    isInitalDateMessage: isInitialDateMessage,
  });
};

ChatRoom.getChatMessageTemplate = function (messageType, senderID) {
  if (senderID == currentUserInfo.shopMemberID) {
    return myMessageTemplate;
  } else if (messageType == MessageType.SYSTEM) {
    return systemMessageTemplate;
  } else {
    return userMessageTemplate;
  }
};

ChatRoom.parseUserProfileURL = function (profileURL) {
  if (profileURL) {
    return Common.getProfileImgUrl(profileURL);
  } else {
    return Common.getProfileImgUrl("");
  }
};

ChatRoom.renderMessage = function (message, isToday, isOtherYear) {
  if (
    message.messageType == MessageType.COMMUNICATIONSTART ||
    message.messageType == MessageType.COMMUNICATIONEND
  ) {
    return ChatRoom.renderCollaborationMessage(message, isToday, isOtherYear);
  } else {
    return ChatRoom.renderChatMessage(message, isToday, isOtherYear);
  }
};

ChatRoom.renderCollaborationMessage = function (message, isToday, isOtherYear) {
  console.log(
    "peacekim:: ChatRoom.renderCollaborationMessage message: " +
      message +
      " isToday: " +
      isToday +
      " isOtherYear: " +
      isOtherYear
  );
  const collaborationInfo = JSON.parse(message.message);
  const userInCollaboration = JSON.parse(
    NativeBridgeDataSource.getUserInfoList(collaborationInfo.userList)
  );
  const displayUserList = ChatRoom.getDisplayUserList(userInCollaboration);
  const meetingID = ChatRoom.getMeetingID(collaborationInfo.meetingId);
  const messageTime = CHAT_UTIL.formatDate(message.insertDate);
  const createdAtYear =
    message.insertDate.substring(0, 4) + getLocalizedString("year") + " ";
  // 協業のタイプを数値から文字列に変換
  const strCollaborationType = CHAT_UTIL.getCollaborationType(
    collaborationInfo.collaborationType
  );

  const html = Mustache.render(collaborationMessageTemplate, {
    messageId: message.messageId,
    roomName: roomName,
    userCount: userInCollaboration.length,
    userList: displayUserList,
    insertDate: message.insertDate,
    // TODO: peacekim:: should check collaborationInfo.collaborationType is string or number
    collaborationType: strCollaborationType,
    meetingId: meetingID,
    isToday: isToday,
    createdAtDay: messageTime.createdAtDay,
    createdAtTime: messageTime.createdAtTime,
    createdAtYear: createdAtYear,
    isOtherYear: isOtherYear,
    isEnded: message.messageType == MessageType.COMMUNICATIONEND ? true : false,
  });
  return message.message.includes("attachedImages") ||
    message.message.includes("attachedVideos")
    ? CHAT_UTIL.htmlDecode(html)
    : html;
};

ChatRoom.getMeetingID = function (meetingID) {
  return typeof meetingID != "undefined" ? 0 : meetingID;
};

ChatRoom.getDisplayUserList = function (userList) {
  console.log("peacekim:: ChatRoom.getDisplayUserList userList: " + userList);
  userList.forEach(function (user) {
    user.profileUrl = Common.getProfileImgUrl(user.profileUrl);
  });
  return userList.length > 3 ? userList.slice(0, 3) : userList;
};

ChatRoom.renderChatMessage = function (message, isToday, isOtherYear) {
  console.log(
    "peacekim:: ChatRoom.renderChatMessage message: " +
      message +
      " isToday: " +
      isToday +
      " isOtherYear: " +
      isOtherYear
  );
  const template = ChatRoom.getChatMessageTemplate(
    message.messageType,
    message.shopMemberId
  );

  const messageTime = CHAT_UTIL.formatDate(message.insertDate);

  const createdAtYear =
    message.insertDate.substring(0, 4) + getLocalizedString("year") + " ";

  const html = Mustache.render(template, {
    text: message.message,
    from: message.loginId,
    messageId: message.messageId,
    shopMemberId: message.shopMemberId,
    profileImage: message.profileUrl,
    createdAtDay: messageTime.createdAtDay,
    createdAtTime: messageTime.createdAtTime,
    createdAtYear: createdAtYear,
    unreadCount: message.unreadCount,
    isOtherYear: isOtherYear,
    isToday: isToday,
  });
  return message.message.includes("attachedImages") ||
    message.message.includes("attachedVideos")
    ? CHAT_UTIL.htmlDecode(html)
    : html;
};
