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

//招待するメンバーを保存する変数
CHAT.globalSelectedUserList = new Array();
CHAT.globalIsInvite = false;

//ログイン中の部屋情報を保存する変数
CHAT.globalLoginParameter;

// fermi coview share
let globalUserInfo = new Object();

var beforeHeight = window.innerHeight;
var beforeWidth = window.innerWidth;
var beforeScroll;

CHAT.saveRoomInfo = function (roomId, roomName) {
  CHAT.globalLoginParameter.roomId = roomId;
  CHAT.globalLoginParameter.roomName = roomName;
  if (CHAT_UTIL.isIOS()) {
    webkit.messageHandlers.roomInfosaveMessageHandlerId.postMessage({
      roomId: roomId,
      roomName: roomName,
    });
  } else if (CHAT_UTIL.isAndroid()) {
    if (roomId == undefined && roomName == undefined) {
      android.saveVisitRoomInfo("", "");
    } else {
      android.saveVisitRoomInfo(roomId, roomName);
    }
  }
};

// #36170 画像パスが存在しない場合はデフォルトの画像を返す
// 存在する場合はプロフィール画像取得用APIのURLを生成して返す
CHAT.getProfileImgUrl = function (path) {
  if (path == undefined || path == "") {
    return ASSET_PATH + "img/noImage.png";
  } else {
    if (path.includes("/mnt")) {
      var userInfo = path.split("/").reverse();
      return (
        CMS_SERVER_URL +
        "/chatapi/user?profileFileName=" +
        userInfo[0] +
        "&profileGetLoginId=" +
        userInfo[1] +
        "&sid=" +
        CHAT.globalLoginParameter.sid +
        "&cmd=12"
      );
    } else {
      return path;
    }
  }
};

// Video のサムネイルファイル生成する
CHAT.createVideoThumbnailAndUpload = function (sourceImage, callback) {
  var fileReader = new FileReader();

  fileReader.onload = function () {
    var blob = new Blob([fileReader.result], { type: sourceImage.type });
    var url = URL.createObjectURL(blob);
    var video = document.createElement("video");
    var timeupdate = function () {
      if (snapImage()) {
        video.removeEventListener("timeupdate", timeupdate);
        video.pause();
      }
    };
    video.addEventListener("loadeddata", function () {
      if (snapImage()) {
        video.removeEventListener("timeupdate", timeupdate);
      }
    });
    var snapImage = function () {
      var canvas = document.createElement("canvas");
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      canvas
        .getContext("2d")
        .drawImage(video, 0, 0, canvas.width, canvas.height);

      fetch(canvas.toDataURL("image/jpeg"))
        .then(function (res) {
          return res.arrayBuffer();
        })
        .then(function (buf) {
          // 回転された画像をFormDataに保存
          const newFile = new File([buf], sourceImage.name, {
            type: "image/jpeg",
          });
          callback(newFile, true);
          // ajax End
        })
        .catch((error) => {
          // fetch Error catch Block
          if (error) {
            console.log(error);
          }
        });
      return true;
    };
    video.addEventListener("timeupdate", timeupdate);
    video.preload = "metadata";
    video.src = url;
    // Load video in Safari / IE11
    video.muted = true;
    video.playsInline = true;
    video.pause();
  };
  fileReader.readAsArrayBuffer(sourceImage);
};

// Ajaxでイメージをアップロードする
CHAT.uploadImage = function (formData) {
  formData.append("roomId", CHAT.globalLoginParameter.roomId);
  formData.append("sid", CHAT.globalLoginParameter.sid);
  jQuery
    .ajax({
      async: true,
      url: CMS_SERVER_URL + "/chatapi/file/upload",
      type: "post",
      data: formData,
      contentType: false,
      processData: false,
      error: function () {
        alert("読み込み失敗");
        CHAT_UI.dismissLoadingIndicator();
      },
    })
    .done(function (res) {
      var imgPath =
        CMS_SERVER_URL +
        "/chatapi/file/getImage?fileName=" +
        res.fileName +
        "&roomId=" +
        CHAT.globalLoginParameter.roomId;
      var imageName = res.fileName;

      // uploadFileの判断
      var extension = imageName
        .substr(imageName.lastIndexOf(".") + 1)
        .toLowerCase();

      // 画像の処理
      if (
        res.fileType == "jpeg" ||
        res.fileType == "jpg" ||
        res.fileType == "png"
      ) {
        if (res.thumbnailPath && res.thumbnailPath.length > 0) {
          imgPath =
            CMS_SERVER_URL +
            "/chatapi/file/getImage?fileName=" +
            res.thumbImageFileName +
            "&roomId=" +
            CHAT.globalLoginParameter.roomId;
          imageName = res.thumbImageFileName;
        }
        let downloadPath =
          CMS_SERVER_URL +
          "/chatapi/file/download?fileName=" +
          imageName +
          "&roomId=" +
          CHAT.globalLoginParameter.roomId;
        // アップロードが終了した後ローディング画面から離れてメッセージをメッセージを転送する
        const lightbox = $("<a/>", {
          "data-lightbox": "attachedImages",
          "data-title": imageName,
        });
        const image = $("<img/>", {
          src: imgPath,
          width: "auto",
          style: "max-width:100%",
          "data-toggle": "modal",
          onclick: "imageModal(this);",
        });
        const downloadIcon = $("<a/>", {
          href: downloadPath,
          class: "fa fa-download",
          download: res.fileName,
        });

        lightbox.append(image);
        lightbox.append(downloadIcon);
        let text = lightbox.prop("outerHTML");
        let encodedText;
        try {
          encodedText = encodeURIComponent(text);
        } catch (e) {
          encodedText = text;
        }

        socket.emit(
          "createMessage",
          {
            text: encodedText + messageSeperator + MessageType.IMAGE,
          },
          1
        );
      } else {
        // 動画の処理
        if (res.thumbnailPath && res.thumbnailPath.length > 0) {
          imgPath =
            CMS_SERVER_URL +
            "/chatapi/file/getImage?fileName=" +
            res.thumbImageFileName +
            "&roomId=" +
            CHAT.globalLoginParameter.roomId;
        }

        let downloadPath =
          CMS_SERVER_URL +
          "/chatapi/file/download?fileName=" +
          imageName +
          "&roomId=" +
          CHAT.globalLoginParameter.roomId;

        var videoSrc =
          CMS_SERVER_URL +
          "/chatapi/file/getImage?fileName=" +
          res.fileName +
          "&roomId=" +
          CHAT.globalLoginParameter.roomId;
        const totalDiv = $("<div/>", { id: "attachedImages" });
        const videoTag = $("<video/>", {
          controls: "true",
          width: "auto",
          style: "max-width:100%",
        });
        const source = $("<source/>", { src: videoSrc });
        const downloadIcon = $("<a/>", {
          href: downloadPath,
          class: "fa fa-download",
          download: res.fileName,
        });

        videoTag.append(source);
        totalDiv.append(videoTag);
        totalDiv.append(downloadIcon);

        let text = totalDiv.prop("outerHTML");
        let encodedText;
        try {
          encodedText = encodeURIComponent(text);
        } catch (e) {
          encodedText = text;
        }

        socket.emit(
          "createMessage",
          {
            text: encodedText + messageSeperator + MessageType.VIDEO,
          },
          1
        );
      }

      $(".overlay").removeClass("active undismissable");
      $(".loader").removeClass("active");
      CHAT_UI.dismissLoadingIndicator();
    });
};

CHAT.createGetDataUrl = function (fileName, roomId) {
  var filePath =
    CMS_SERVER_URL +
    "/chatapi/file/getImage?sid=" +
    CHAT.globalLoginParameter.sid +
    "&fileName=" +
    fileName +
    "&roomId=" +
    roomId;
  return filePath;
};

// Thumbnailのファイルを生成する。
CHAT.createThumbnailAndUpload = function (sourceImage, callback) {
  const fileReader = new FileReader();
  const img = new Image();
  fileReader.onloadend = function () {
    img.src = fileReader.result;
  };

  img.onload = function () {
    const elem = document.createElement("canvas");
    var rate;
    var width = img.width;
    var height = img.height;
    if (img.width <= 500 && img.height <= 500) {
      callback(undefined, false);
      return;
    }

    if (img.width > img.height) {
      rate = 500 / img.width;
    } else {
      rate = 500 / img.height;
    }
    elem.width = width * rate;
    elem.height = height * rate;

    const ctx = elem.getContext("2d");

    ctx.drawImage(
      img,
      0,
      0,
      img.width,
      img.height,
      0,
      0,
      elem.width,
      elem.height
    );
    // ctx.drawImage(img, 0, 0, width, height);

    fetch(elem.toDataURL("image/jpeg"))
      .then(function (res) {
        return res.arrayBuffer();
      })
      .then(function (buf) {
        const newFile = new File([buf], sourceImage.name, {
          type: "image/jpeg",
        });

        callback(newFile, true);
      })
      .catch((error) => {
        // fetch Error catch Block
        if (error) {
          console.log(error);
        }
      });
  };

  fileReader.readAsDataURL(sourceImage);
};

// 該当チャットルームに参加するためログイン情報をサーバに渡す
getLoginParameter = function (
  sid,
  loginId,
  shopName,
  roomId = undefined,
  roomName = undefined,
  languageCode,
  shopMemberId
) {
  var loginParam = new Object();
  loginParam.sid = sid;
  loginParam.loginId = loginId;
  loginParam.shopName = shopName;
  loginParam.roomId = roomId;
  loginParam.roomName = roomName;
  loginParam.shopMemberId = shopMemberId;

  CHAT.globalLoginParameter = loginParam;

  if (!languageCode) {
    languageCode = "en";
  }

  // fermi coview share
  globalUserInfo.sid = sid;
  globalUserInfo.loginId = shopName + "_" + loginId;
  globalUserInfo.shopName = shopName;
  globalUserInfo.roomId = roomId;
  globalUserInfo.roomName = roomName;
  globalUserInfo.languageCode = languageCode;

  CHAT_UI.htmlElementTextInitialize(languageCode);
  CHAT_UI.dismissLoadingIndicator();
};

// for android native call
CHAT.leaveRoom = function () {
  socket.emit("leaveRoom", function () {});
};

document.addEventListener("DOMContentLoaded", function () {
  // ルーム名変更イベント
  $(".change_room_name_btn button").click(function () {
    $("form").submit();
  });

  // 検索アイコン押下イベント
  $(".nav_item_wrap .search_menu").click(function () {
    $(".nav_item_wrap").addClass("none");
    $(".footer-wrap").addClass("none");
    $(".chat_room_src_form").removeClass("none");
    $(".room_container").addClass("none");
    $(".overlay_src_msg").removeClass("none");
    // フィルタ表示
    $("#filter").removeClass("none");
    $("#user_list").addClass("none");

    $('.chat_room_src_form input[type="search"]').focus();
    $("#searchMessage").addClass("onfocus");
    $(".chat_list").removeClass("none");
  });

  $(".chat_room_src_form .cancel").click(function () {
    $(".nav_item_wrap").removeClass("none");
    $(".footer-wrap").removeClass("none");
    $(".chat_room_src_form").addClass("none");
    $(".chat_room_src_form input").val("");
    $(".room_container").removeClass("none");
    $(".overlay_src_msg").empty();
    // ユーザーリスト表示
    $("#filter").addClass("none");
    $("#user_list").removeClass("none");

    $('.chat_room_src_form input[type="search"]').blur();
    $("#searchMessage").removeClass("onfocus");
    $(".chat_list").addClass("none");
    CHAT_UI.scrollToBottom();
  });

  $('.chat_room_src_form input[type="search"]').click(function () {
    if ($("#searchMessage").hasClass("onfocus")) {
      $("#searchMessage").removeClass("onfocus");
      $("#searchMessage").blur();
    } else {
      $("#searchMessage").addClass("onfocus");
      $("#searchMessage").focus();
    }
  });

  $("#searchMessage").blur(function () {
    $("#searchMessage").removeClass("onfocus");
  });

  // フィルタ選択イベント
  $(document).on("click", "#filter .img_wrap", function (event) {
    // チェックアイコン追加
    $(this).toggleClass("filter");
  });

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

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

  $("#chat_add_user .search_form .cancel").click(function () {
    let roomListTitle = getLocalizedString("inviteUsersSubtitle");
    $("#addUserTitle").text(roomListTitle);
  });

  $("#chatMakeRoom .search_form .cancel").click(function () {
    let roomListTitle = getLocalizedString("createRoomTitle");
    $("#makeRoomTitle").text(roomListTitle);
  });

  // チャットメンバー検索
  $('#chat .search_form input[type="search"]').keyup(function (e) {
    var rooms;
    var keyword = $('#chat .search_form input[type="search"]').val();
    if (e.KeyCode == 13 || e.key == "Enter") {
      if (keyword.length != 0 && keyword != "") {
        $('#chat .search_form input[type="search"]').blur();
        return;
      }
    } else if (keyword == "" || keyword.length < 2) {
      $(".overlay_src_msg").empty();
      return;
    }
    CHAT.searchRoom(keyword, rooms);
    if (e.KeyCode == 13 || e.key == "Enter") {
      $('#chat .search_form input[type="search"]').blur();
      return;
    }
  });
  // iOSキーボード変換検知用
  $('#chat .search_form input[type="search"]').on(
    "compositionend",
    function () {
      if (CHAT_UTIL.isIOS()) {
        var rooms;
        var keyword = $('#chat .search_form input[type="search"]').val();
        CHAT.searchRoom(keyword, rooms);
      }
    }
  );

  var footerHeight = $(".footer-wrap").height();
  window.addEventListener("resize", function () {
    var afterHeight = window.innerHeight;
    var afterWidth = window.innerWidth;
    var moreScroll = beforeHeight - afterHeight;
    if (beforeHeight > afterHeight && beforeHeight - afterHeight > 50) {
      if (CHAT_UTIL.isIOS()) {
        window.scrollTo(0, beforeScroll + moreScroll);
      } else if (beforeWidth == afterWidth) {
        //キーボード表示時
        $(".room_container").css("margin-bottom", 0);
        window.scrollTo(
          0,
          beforeScroll + moreScroll - $(".footer_content_b").height()
        );
      } else {
        //画面回転時
        window.scrollTo(
          0,
          beforeScroll + moreScroll * 2 - $(".footer_content_b").height()
        );
      }
    } else if (beforeHeight < afterHeight) {
      $(".room_container").css("margin-bottom", footerHeight);
      if (CHAT_UTIL.isIOS()) {
        window.scrollTo(0, beforeScroll + moreScroll);
      } else if (beforeWidth == afterWidth) {
        //キーボード非表示
        window.scrollTo(
          0,
          beforeScroll + moreScroll + $(".footer_content_b").height()
        );
      } else {
        //画面回転時
        window.scrollTo(
          0,
          beforeScroll + moreScroll * 2 + $(".footer_content_b").height()
        );
      }
    }
    beforeHeight = window.innerHeight;
    beforeWidth = window.innerWidth;
  });

  $("#messageInput").focusin(function (e) {
    beforeHeight = window.innerHeight;
    beforeWidth = window.innerWidth;
    beforeScroll = window.scrollY;
  });
  // チャットルーム
  // メッセージ検索イベント
  $('.chat_room_src_form input[type="search"]').keyup(function (e) {
    let workVal = "";
    var keyword = $('.chat_room_src_form input[type="search"]').val();
    if (e.key == "Enter" || e.KeyCode == 13) {
      if (keyword != "" && keyword.length != 0) {
        $('.chat_room_src_form input[type="search"]').blur();
        return;
      }
    } else if (keyword == "" || keyword.length < 2) {
      $(".overlay_src_msg").empty();
      return;
    }
    CHAT.searchMessage(keyword, workVal);
    if (e.key == "Enter" || e.KeyCode == 13) {
      $("#searchMessage").removeClass("onfocus");
      $('.chat_room_src_form input[type="search"]').blur();
      return;
    }
  });
  // iOSキーボード変換検知用
  $('.chat_room_src_form input[type="search"]').on(
    "compositionend",
    function () {
      if (CHAT_UTIL.isIOS()) {
        let workVal = "";
        var keyword = $('.chat_room_src_form input[type="search"]').val();
        CHAT.searchMessage(keyword, workVal);
      }
    }
  );

  $(document).on("click", ".filter_img", function (event) {
    let workVal = "";
    var keyword = $('.chat_room_src_form input[type="search"]').val();
    $(".overlay_src_msg").empty();
    let checkedUserList = getCheckedUserList();
    if (keyword.length == 1) {
      return;
    }
    const messages = CHAT_DB.searchMessages(keyword, checkedUserList.join(","));
    var userMessageTemplate = getTemplate(TemplateURL.USER_MESSAGE);
    var myMessageTemplate = getTemplate(TemplateURL.MY_MESSAGE);

    let jQueryMessages = $(".overlay_src_msg");
    messages.forEach(function (message) {
      let template = userMessageTemplate;
      if (message.shopMemberId == CHAT.globalLoginParameter.shopMemberId) {
        template = myMessageTemplate;
      }
      if (message.messageType == MessageType.SYSTEM) {
        template = systemMessageTemplate;
      }
      let messageTime = CHAT_UTIL.formatDate(message.insertDate);
      // ユーザの様式を読み込む

      if (message.profileUrl) {
        message.profileUrl = CHAT.getProfileImgUrl(message.profileUrl);
      } else {
        message.profileUrl = CHAT.getProfileImgUrl("");
      }
      message.message = message.message.toString();
      var replacePath = message.message;
      replacePath = replacePath.replaceAll(
        "?fileName=",
        "?sid=" + CHAT.globalLoginParameter.sid + "&fileName="
      );
      message.message = replacePath;

      let html = Mustache.render(template, {
        text: message.message,
        from: message.loginId,
        shopMemberId: message.shopMemberId,
        profileImage: message.profileUrl,
        createdAtDay: messageTime.createdAtDay,
        createdAtTime: messageTime.createdAtTime,
      });
      html =
        message.message.includes("attachedImages") ||
        message.message.includes("attachedVideos")
          ? CHAT_UTIL.htmlDecode(html)
          : html;
      workVal = html + workVal;
    });
    jQueryMessages.prepend(workVal);
  });
});

var getCheckedUserList = function () {
  let checkedUserList = [];
  $(".img_wrap.filter").each(function (user) {
    const selectedUser = $(".img_wrap.filter")[user];
    checkedUserList.push($(selectedUser).data("user-id"));
  });
  return checkedUserList;
};

// チャットルーム検索
CHAT.searchRoom = function (keyword, rooms) {
  const overlayMessage = $(".overlay_src_msg");
  overlayMessage.empty();
  rooms = CHAT_DB.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 = ASSET_PATH + "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 = CHAT.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.searchMessage = function (keyword, workVal) {
  $(".overlay_src_msg").empty();
  var checkedUserList = [];
  $(".img_wrap.filter").each(function (user) {
    const selectedUser = $(".img_wrap.filter")[user];
    checkedUserList.push($(selectedUser).data("user-id"));
  });
  var messages = CHAT_DB.searchMessages(keyword, checkedUserList.join(","));
  var userMessageTemplate = getTemplate(TemplateURL.USER_MESSAGE);
  var myMessageTemplate = getTemplate(TemplateURL.MY_MESSAGE);

  let jQueryMessages = $(".overlay_src_msg");
  messages.forEach(function (message) {
    let template = userMessageTemplate;
    if (message.shopMemberId == CHAT.globalLoginParameter.shopMemberId) {
      template = myMessageTemplate;
    }
    if (message.messageType == MessageType.SYSTEM) {
      template = systemMessageTemplate;
    }
    let messageTime = CHAT_UTIL.formatDate(message.insertDate);
    if (message.profileUrl) {
      message.profileUrl = CHAT.getProfileImgUrl(message.profileUrl);
    } else {
      message.profileUrl = CHAT.getProfileImgUrl("");
    }
    message.message = message.message.toString();
    var replacePath = message.message;
    replacePath = replacePath.replaceAll(
      "?fileName=",
      "?sid=" + CHAT.globalLoginParameter.sid + "&fileName="
    );
    message.message = replacePath;
    let html = Mustache.render(template, {
      text: message.message,
      from: message.loginId,
      shopMemberId: message.shopMemberId,
      profileImage: message.profileUrl,
      createdAtDay: messageTime.createdAtDay,
      createdAtTime: messageTime.createdAtTime,
    });
    html =
      message.message.includes("attachedImages") ||
      message.message.includes("attachedVideos")
        ? CHAT_UTIL.htmlDecode(html)
        : html;
    workVal = html + workVal;
  });
  jQueryMessages.prepend(workVal);
  if (messages.length == 0) {
    const noResultMsg = getNoResultMessage();
    jQueryMessages.append(noResultMsg);
  }
};
