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

document.addEventListener("DOMContentLoaded", function () {
  // アーカイブ検索
  ArchiveUI.bindArchiveSearch();
  // iOSキーボード変換検知用
  ArchiveUI.bindiOSKeyBoardEvent();
});

ArchiveUI.refreshSearchScreen = function (keyword) {
  const archiveList = NativeBridgeDataSource.getArchiveByName(keyword);
  ArchiveUI.getArchiveTemplate().then(function (archiveTemplate) {
    archiveList.forEach(function (archive) {
      const typeImage = ArchiveUI.getArchiveTypeIconURL(archive.archiveType);
      let html = ArchiveUI.renderArchiveTemplate(
        archiveTemplate,
        archive.archiveId,
        archive.archiveName,
        archive.archiveDate,
        typeImage
      );

      let obj = jQuery.parseHTML(html);
      $(".overlay_src_msg").prepend(obj);
    });
  });
};

ArchiveUI.getArchiveTypeIconURL = function (type) {
  switch (type) {
    case ARCHIVE_TYPE.PICTURE:
      return "icon/icon_collabo_picture.svg";
    case ARCHIVE_TYPE.VIDEO:
      return "icon/icon_collabo_videocam.svg";
    case ARCHIVE_TYPE.VOICE:
      return "icon/icon_collabo_headset.svg";
    case ARCHIVE_TYPE.DOCUMENT:
      return "icon/icon_collabo_document.svg";
    default:
      return "";
  }
};

ArchiveUI.getArchiveTemplate = function () {
  return new Promise(function (resolve, reject) {
    $.get({ url: TemplateURL.ARCHIVE_LIST, async: false }, function (text) {
      resolve(text);
    });
  });
};

ArchiveUI.bindArchiveSearch = function () {
  const searchInput = $('#archive .search_form input[type="search"]');
  searchInput.keyup(function (e) {
    const keyword = searchInput.val();
    const enterKeyPressed = e.KeyCode == 13 || e.key == "Enter";
    const keywordEmpty = keyword == "" || keyword.length < 2;
    const keywordNotEmpty = keyword.length != 0 && keyword != "";
    if (enterKeyPressed) {
      if (keywordNotEmpty) {
        searchInput.blur();
        return;
      }
    } else if (keywordEmpty) {
      $(".overlay_src_msg").empty();
      return;
    }
    $(".overlay_src_msg").empty();

    ArchiveUI.refreshSearchScreen(keyword);

    if (enterKeyPressed) {
      searchInput.blur();
      return;
    }
    // 検索結果を表示
  });
};

ArchiveUI.bindiOSKeyBoardEvent = function () {
  const searchInput = $('#archive .search_form input[type="search"]');
  searchInput.on("compositionend", function () {
    if (deviceInfo.isiOS()) {
      const keyword = searchInput.val();
      $(".overlay_src_msg").empty();
      ArchiveUI.refreshSearchScreen(keyword);
    }
  });
};

ArchiveUI.renderArchiveTemplate = function (
  html,
  archiveId,
  archiveName,
  archiveDate,
  typeImageURL
) {
  return Mustache.render(html, {
    archiveId: archiveId,
    fileName: archiveName,
    insertDate: archiveDate,
    typeImage: typeImageURL,
  });
};

/*****************
 *  アーカイブ詳細
 ****************/
ArchiveUI.refreshArchiveDetailScreen = function (archiveId) {
  // loadingIndicatorを表示
  Common.showLoadingIndicator();

  // 初期化
  $("#archiveDetail").html("");

  if (serverInfo.isOnline == true) {
    NativeBridgeDelegate.updateArchiveDetail(archiveId);
  }

  // アーカイブ詳細取得
  const archive = NativeBridgeDataSource.getArchiveDetail(archiveId);

  // template archive detail
  ArchiveUI.appendArchiveDetailScreen(archive);

  // setup player
  ArchiveUI.appendPlayer(archive);

  // append attended users
  ArchiveUI.appendAttendUsers(archive.attendUserIds);

  // set languages
  currentUserInfo.configureLanguage();

  // TODO: peacekim:: check localization works or not
  $(".ttl_detail").text(getLocalizedString("detail"));
  $("#archiveFileName").text(getLocalizedString("archiveFileName"));
  $("#archiveInsertDate").text(getLocalizedString("archiveInsertDate"));
  $("#archiveRoomName").text(getLocalizedString("archiveRoomName"));
  $("#archiveSaveUser").text(getLocalizedString("archiveSaveUser"));
  $("#archiveAttendUser").text(getLocalizedString("archiveAttendUser"));

  // チャットルームへのリンク付け
  document.getElementById("joinChatRoom").onclick = function () {
    NativeBridgeDelegate.joinRoom(archive.roomId, archive.roomName);
  };

  // loadingIndicatorを非表示
  Common.dismissLoadingIndicator();
};

ArchiveUI.appendArchiveDetailScreen = function (archive) {
  // 保存ユーザ情報を取得
  const userInfo = NativeBridgeDataSource.getUserInfo(archive.saveUserId);
  userInfo.profileUrl = Common.getProfileImgUrl(userInfo.profileUrl);

  // アーカイブ詳細の様式を読み込む
  const archiveDetailTemplate = getTemplate(TemplateURL.ARCHIVE_DETAIL);

  // アーカイブ情報を表示
  const html = Mustache.render(archiveDetailTemplate, {
    fileName: archive.archiveName,
    insertDate: archive.archiveDate,
    chatRoomName: archive.roomName,
    chatRoomId: archive.roomId,
    profileImage: userInfo.profileUrl,
    userName: userInfo.shopMemberName,
    userId: userInfo.shopMemberId,
  });

  var obj = $(jQuery.parseHTML(html)).on("click", function () {});
  $("#archiveDetail").append(obj);
};

ArchiveUI.appendPlayer = function (archive) {
  // プレイヤーの切り替え
  const archiveFilePath = ArchiveUI.createGetDataUrl(
    archive.filePath,
    archive.roomId
  );

  switch (archive.archiveType) {
    case "0": // 画像
    case 0:
      ArchiveUI.appendImageTypePlayer(archiveFilePath);
      break;
    case "1": // 動画
    case 1:
      ArchiveUI.appendVideoTypePlayer(archiveFilePath);
      break;
    case "2": // 音声
    case 2:
      ArchiveUI.appendVoiceTypePlayer(archiveFilePath);
      break;
    case "3": // 文書
    case 3:
      // リリースに文書とその他は含めないため今回は非表示
      break;
    default:
    // リリースに文書とその他は含めないため今回は非表示
  }
};

ArchiveUI.appendImageTypePlayer = function (filePath) {
  $("#archive_player").prepend(
    '<img class="archive_player" src="' + filePath + '" />'
  );
};

ArchiveUI.appendVideoTypePlayer = function (filePath) {
  if (deviceInfo.isiOS()) {
    $("#archive_player").prepend(
      '<video class="archive_player" controls autoplay playsinline controlsList="nodownload"><source src="' +
        filePath +
        '" type="video/mp4"><source src="' +
        filePath +
        '" type="video/ogv"><source src="' +
        filePath +
        '" type="video/webm"></video>'
    );
  } else {
    $("#archive_player").prepend(
      '<video class="archive_player" src=' +
        filePath +
        ' controls autoplay playsinline controlsList="nodownload"></video>'
    );
  }
};

ArchiveUI.appendVoiceTypePlayer = function (filePath) {
  if (deviceInfo.isiOS()) {
    $("#archive_player").prepend(
      '<audio class="archive_audio_player" controls controlsList="nodownload"><source src="' +
        filePath +
        '" type="audio/wav"><source src="' +
        filePath +
        '" type="audio/ogg"></audio>'
    );
  } else {
    $("#archive_player").prepend(
      '<audio class="archive_audio_player" src=' +
        filePath +
        ' controls controlsList="nodownload"></audio>'
    );
  }
  $("#archive_player").prepend(
    '<img class="archive_player" src=' + "./img/capture.png" + " />"
  );
};

ArchiveUI.appendAttendUsers = function (attendedUserList) {
  // ユーザの様式を読み込む
  const archiveUserTemplate = getTemplate(TemplateURL.ARCHIVE_USER);

  if (typeof android != "undefined") {
    // ios実装不要
    attendedUserList = JSON.parse(attendedUserList);
  }

  attendedUserList.forEach(function (user) {
    if (user == "") {
      return;
    }
    const userInfo = NativeBridgeDataSource.getUserInfo(user);
    userInfo.profileUrl = Common.getProfileImgUrl(userInfo.profileUrl);
    const html = Mustache.render(archiveUserTemplate, {
      profileImage: userInfo.profileUrl,
      userName: userInfo.shopMemberName,
    });

    const obj = $(jQuery.parseHTML(html)).on("click", function () {
      // ネームカード表示
      Namecard.makeNameCard(user);
    });

    $("#attendUser").append(obj);
  });
};

ArchiveUI.createGetDataUrl = function (fileName, roomId) {
  return (
    serverInfo.cmsURL +
    "/chatapi/file/getImage?sid=" +
    currentUserInfo.sid +
    "&fileName=" +
    fileName +
    "&roomId=" +
    roomId
  );
};

// アーカイブ一覧
ArchiveUI.refreshArchiveScreen = function () {
  // loadingIndicatorを表示
  Common.showLoadingIndicator();

  // 初期化
  $("#archiveList").html("");

  // アーカイブの様式を読み込む
  const archiveTemplate = getTemplate(TemplateURL.ARCHIVE);

  // アーカイブ一覧取得
  if (serverInfo.isOnline == true) {
    NativeBridgeDelegate.updateArchiveList();
  }

  // ローカルDBのデータを表示
  const archiveList = NativeBridgeDataSource.getArchiveList();
  if (typeof archiveList == "undefined") {
    Common.dismissLoadingIndicator();
    return;
  }
  archiveList.forEach(function (archive) {
    var typeImage = "";
    switch (archive.archiveType) {
      case ARCHIVE_TYPE.PICTURE: // 画像
        typeImage = "icon/icon_collabo_picture.svg";
        break;
      case ARCHIVE_TYPE.VIDEO: // 動画
        typeImage = "icon/icon_collabo_videocam.svg";
        break;
      case ARCHIVE_TYPE.VOICE: // 音声
        typeImage = "icon/icon_collabo_headset.svg";
        break;
      case ARCHIVE_TYPE.DOCUMENT: // 文書
        typeImage = "icon/icon_collabo_document.svg";
        break;
      default:
        // その他
        typeImage = "";
        break;
    }
    const html = Mustache.render(archiveTemplate, {
      archiveId: archive.archiveId,
      fileName: archive.archiveName,
      insertDate: archive.archiveDate,
      typeImage: typeImage,
    });
    const obj = $(jQuery.parseHTML(html)).on("click", function () {});
    $("#archiveList").prepend(obj);
  });

  // loadingIndicatorを非表示
  Common.dismissLoadingIndicator();
};
