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

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

ARCHIVE_UI.refreshSearchScreen = function (keyword) {
  const archiveList = CHAT_DB.getArchiveByName(keyword);
  const typeImage = getArchiveTypeIconURL(archive.archiveType);

  getArchiveTemplate().then(function (archiveTemplate) {
    archiveList.forEach(function (archive) {
      let html = renderArchiveTemplate(
        archiveTemplate,
        archive.archiveId,
        archive.archiveName,
        archive.archiveDate,
        typeImage
      );

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

//* UTILS *//
const ARCHIVE_TYPE = {
  PICTURE: 0,
  VIDEO: 1,
  VOICE: 2,
  DOCUMENT: 3,
};

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

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

var bindArchiveSearch = function () {
  const searchInput = $('#archive .search_form input[type="search"]');
  searchInput.keyup(function (e) {
    var 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();

    ARCHIVE_UI.refreshSearchScreen(keyword);

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

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

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