var beforeHeight = window.innerHeight;
var beforeWidth = window.innerWidth;
var beforeScroll;
var roomName = "";
var initialLoading = true;
var ChatRoom = {};

window.onscroll = function () {
  if (beforeScroll == window.scrollY) {
    return;
  }
  beforeScroll = window.scrollY;
  const beforeHeight = $(".room_container").height();
  messageCount = $(".chat_message").length;
  // TODO: peacekim :: check this condition
  if ($(this).scrollTop() === 0 && messageCount >= PagingSize.MESSAGE) {
    setTimeout(function () {
      if (!$("#chatLoader").is(":visible")) {
        // display loading indicator in chat message
        let loader = $(
          '<div id="chatLoader" class="text-center"><div class="spinner-grow spinner-grow-sm" role="status" /></div>'
        );
        $("#messages").append(loader);
        // get lastest message id and update message from server via native
        const messageID = $($(".chat_message").last()).data("messageid");
        NativeBridgeDelegate.updatePreMessage(messageID);
        let messages = NativeBridgeDataSource.getMessagesByMessageID(messageID);
        // prepend message
        ChatRoom.prependMessage(messages);
        // hide loading indicator
        loader.remove();
        var afterHeight = $(".room_container").height();
        window.scroll(0, afterHeight - beforeHeight);
      }
    }, 0);
  }
};

document.addEventListener("DOMContentLoaded", function () {
  // 検索イベントバインディング
  ChatRoom.bindSearchUI();

  // 画面サイズ変更イベントバインディング
  ChatRoom.bindResize();

  // メッセージ入力イベントバインディング
  ChatRoom.bindMessageInput();

  // 下スクロールでユーザーリストを非表示
  ChatRoom.bindUserListDisplayToggle();
});

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

ChatRoom.bindMessageInput = function () {
  $("#messageInput").focusin(function (e) {
    beforeHeight = window.innerHeight;
    beforeWidth = window.innerWidth;
    beforeScroll = window.scrollY;
  });

  $(".message_input_form").on("focus", function (e) {
    setTimeout(function () {
      $(".message_input_send").removeClass("none");
      $(".attach_file").addClass("none");
      $(".footer_content_b").addClass("none");
    }, 10);
  });

  $(".message_input_form").on("focusout", function (e) {
    setTimeout(function () {
      if ($(e.relatedTarget).hasClass("message_input_send")) {
        ChatRoom.sendMessage();
      } else {
        $(".message_input_send").addClass("none");
        $(".attach_file").removeClass("none");
        $(".footer_content_b").removeClass("none");
      }
    }, 10);
  });
};

// 下スクロールでユーザーリストを非表示
ChatRoom.bindUserListDisplayToggle = function () {
  let startPos = 0;
  let winScrollTop = 0;
  $(window).on("scroll", function () {
    winScrollTop = $(this).scrollTop();
    if (winScrollTop >= startPos) {
      if (winScrollTop >= 200) {
        $("#chat_room .user_list").addClass("hide");
      }
    } else {
      $("#chat_room .user_list").removeClass("hide");
    }
    startPos = winScrollTop;
  });
};

// 画像の読み込みが全て終わったタイミングでコールバック実行
// FIXME 追加読み込みの場合は差分の画像のみ監視すべきだが、現状新規入室時にしか対応出来ていない。
ChatRoom.waitForLoadingVideo = function (div, callback) {
  Common.showLoadingIndicator();
  // var imgs = document.getElementsByTagName("video");
  let video = div.find("video");
  let count = video.length;
  if (count == 0) callback();
  let loaded = 0;
  video.each(function () {
    this.addEventListener("loadeddata", function (e) {
      loaded++;
      if (loaded === count) {
        callback();
        Common.dismissLoadingIndicator();
      }
    });
  });
};

ChatRoom.waitForLoadingImage = function (div, callback) {
  let imgs = div.find("img");
  let count = imgs.length;
  if (count == 0) callback();
  let loaded = 0;
  imgs
    .one("load", function (e) {
      // イメージが読み込まれた
      loaded++;
      if (loaded === count) {
        callback();
      }
    })
    .each(function () {
      if (this.complete || this.readyState === readyState.COMPLETED) {
        $(this).trigger("load");
      }
    });
};

ChatRoom.scrollToBottom = function (animated = true) {
  const messages = $(".room_contents");
  const scrollHeight = messages.prop("scrollHeight");

  $("html, body").animate(
    {
      scrollTop: scrollHeight,
    },
    animated ? 100 : 0,
    function () {
      initialLoading = false;
      Common.dismissLoadingIndicator();
    }
  );
};

ChatRoom.refreshForOnline = function () {
  $("#videoUploadButton").removeClass("ui-state-disabled");
  $("#imageInputButton").removeClass("ui-state-disabled");
  $("#messageSend").prop("disabled", false);
  $("#messageInput").prop("disabled", false);
  $("#messageInput").prop("placeholder", "メッセージを入力してください");
  $("#room_name_change_button").removeClass("ui-state-disabled");
  $("#add_user_button").removeClass("ui-state-disabled");
  $(".fa-download").show();

  if (typeof $("#roomTitle").val() != "undefined") {
    CHAT_SOCKET.initialJoin();
  }
};

ChatRoom.refreshForOffline = function () {
  $("#videoUploadButton").addClass("ui-state-disabled");
  $("#imageInputButton").addClass("ui-state-disabled");
  $("#messageSend").prop("disabled", true);
  $("#messageInput").prop("disabled", true);
  $("#messageInput").prop("placeholder", "");
  $("#room_name_change_button").addClass("ui-state-disabled");
  $("#add_user_button").addClass("ui-state-disabled");
  $(".fa-download").hide();
};
