"use strict";

exports.__esModule = true;
exports.useChatMessage = useChatMessage;
exports.default = void 0;

var _react = require("react");

var _reactUse = require("react-use");

function useChatMessage({
  subsonic,
  isLoggedIn,
  delay = 5000,
  setLoading
}) {
  const [chatMessages, setChatMessages] = (0, _react.useState)([]);
  const [since, setSince] = (0, _react.useState)(null);

  const updateChatMessages = () => {
    // console.log('fetching', since, isLoggedIn);
    if (!isLoggedIn) {
      return;
    }

    if (setLoading) {
      setLoading(() => 'chat');
    }

    subsonic.getChatMessages(since).then(res => {
      // console.log('res', res);
      setChatMessages(old => {
        var _res$chatMessages;

        return old.concat((res == null ? void 0 : (_res$chatMessages = res.chatMessages) == null ? void 0 : _res$chatMessages.chatMessage) || []).sort((a, b) => a.time - b.time);
      });
      setSince(() => Date.now());
      setLoading(() => null);
    });
  };

  const clearChatMessages = () => {
    setChatMessages(() => []);
    setSince(() => Date.now());
  };

  (0, _reactUse.useInterval)(() => {
    updateChatMessages();
  }, delay);

  const addMessage = msg => {
    subsonic.addChatMessage(msg);
  };

  return {
    chatMessages,
    addMessage,
    updateChatMessages,
    clearChatMessages
  };
}

var _default = useChatMessage;
exports.default = _default;