var bindOnNewMessage = function () {
  // New Message
  // #36170
  socket.on(SOCKET_KEY.NEW_MESSAGE, function (message, roomId, roomName) {
    console.log(message);
    const systemMessageTemplate = getTemplate(TemplateURL.SYSTEM_MESSAGE);

    const unwrappedMessageInfo = decodeMessage(message.text);
    if (
      unwrappedMessageInfo ==
      DATA_MESSAGE_SCHEME + FINISH_ALL_COLLABORATION_SIGNAL
    ) {
      cleanUpCollaborationMessage();
      return;
    }

    if (unwrappedMessageInfo.includes(messageSeperator)) {
      const messageInfo = unwrappedMessageInfo.split(messageSeperator);
      const messageText = messageInfo[0];
      const messageType = messageInfo[1];

      if (
        messageType == MessageType.COMMUNICATIONSTART ||
        messageType == MessageType.COMMUNICATIONEND
      ) {
        addCollaborationMessage(
          messageInfo,
          message.userId,
          roomName,
          message.insertDate,
          message.createdAt
        );
      } else {
        addTextMessage(messageText, message, socket.id);
      }
    }

    // 画像、動画の描画を待ってからスクロール
    setTimeout(function () {
      CHAT_UI.scrollToBottom();
    }, 300);
  });
};

var decodeMessage = function (text) {
  try {
    return decodeURIComponent(text);
  } catch (e) {
    return text;
  }
};

var addCollaborationMessage = function (
  messageInfo,
  userID,
  roomName,
  insertDate,
  createdAt
) {
  const collaborationType = messageInfo[2];
  const meetingID = getMeetingID(collaborationType, messageInfo);
  const userInCollaboration = getUserInfoList(userID);

  userInCollaboration.forEach(function (user) {
    user.profileUrl = CHAT.getProfileImgUrl(user.profileUrl);
  });

  const openCollaborationMessageTemplate = getTemplate(
    TemplateURL.OPEN_COLLABORATION_MESSAGE
  );

  const html = renderCollaborationMessage(
    openCollaborationMessageTemplate,
    roomName,
    userInCollaboration,
    insertDate,
    collaborationType,
    meetingID,
    createdAt
  );

  $("#messages").append(html);
};

var getMeetingID = function (collaborationType, messageInfo) {
  if (
    collaborationType ==
    CHAT_UTIL.getCollaborationType(CollaborationTypeKey.DOCUMENT)
  ) {
    return messageInfo[3];
  } else {
    return 0;
  }
};

var renderCollaborationMessage = function (
  template,
  roomName,
  userList,
  insertDate,
  collaborationType,
  meetingID,
  createdAt
) {
  let messageTime = CHAT_UTIL.formatDate(createdAt);
  return Mustache.render(template, {
    roomName: roomName,
    messageId: 0,
    userCount: 1,
    userList: userList,
    insertDate: insertDate,
    collaborationType: collaborationType,
    isToday: true,
    meetingId: meetingID,
    createdAtDay: messageTime.createdAtDay,
    createdAtTime: messageTime.createdAtTime,
    isOtherYear: false,
  });
};

var addTextMessage = function (messageText, message, socketID) {
  const messageTextWithSID = insertSID(messageText);
  const messageSender = getUserInfoList(message.userId);
  const shopMemberName = messageSender[0].shopMemberName;
  const textMessageTemplate = getTextMessageTemplate(message.id === socketID);
  const profileImagePath = CHAT.getProfileImgUrl(message.profileImagePath);
  const html = renderTextMessage(
    textMessageTemplate,
    messageTextWithSID,
    shopMemberName,
    profileImagePath,
    message.userId,
    message.createdAt
  );
  $("#messages").append(html);
};

var renderTextMessage = function (
  template,
  text,
  from,
  profileImagePath,
  userID,
  createdAt
) {
  let messageTime = CHAT_UTIL.formatDate(createdAt);
  let dataInsertedTemplate = Mustache.render(template, {
    text: text,
    from: from,
    messageId: 0,
    profileImage: profileImagePath,
    shopMemberId: userID,
    createdAtDay: messageTime.createdAtDay,
    createdAtTime: messageTime.createdAtTime,
    isToday: true,
  });

  // イメージの場合、img tagを追加する
  if (text.includes("attachedImages") || text.includes("attachedVideos")) {
    return CHAT_UTIL.htmlDecode(dataInsertedTemplate);
  } else {
    return dataInsertedTemplate;
  }
};

var getUserInfoList = function (userID) {
  if (CHAT_UTIL.isIOS()) {
    return JSON.parse(CHAT_DB.getUserInfoList(userID));
  } else if (CHAT_UTIL.isAndroid()) {
    return JSON.parse(android.getUserInfoList(userID));
  }
};

var cleanUpCollaborationMessage = function () {
  $(".collabo_area.start").each(function (index, collaborationMessage) {
    $(collaborationMessage).removeClass("start");
    $(collaborationMessage).addClass("end");
    $(collaborationMessage).addClass("disable");
    $(collaborationMessage)
      .find(".collaboation_join_button")
      .attr("disabled", "disabled");
    $(collaborationMessage)
      .find(".collaboration_join_message")
      .text(getLocalizedString("message_ended"));
  });
};

var insertSID = function (text) {
  let replacePath = text;
  replacePath = replacePath.replaceAll(
    "?fileName=",
    "?sid=" + CHAT.globalLoginParameter.sid + "&fileName="
  );
  return replacePath;
};

var getTextMessageTemplate = function (isSenderMySelf) {
  return getTemplate(
    isSenderMySelf
      ? TemplateURL.MY_MESSAGE // ユーザーが送信したメッセージの場合、自分のメッセージ様式を適用して表示する
      : TemplateURL.USER_MESSAGE
  );
};
