"use strict";

exports.__esModule = true;
exports.default = exports.useRemoteReceiver = exports.RemoteReceiverProvider = exports.RemoteReceiverContext = exports.useRemoteReceiverStorage = void 0;

var _react = _interopRequireWildcard(require("react"));

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

var _propTypes = _interopRequireDefault(require("prop-types"));

var _SubsonicContext = require("subfirelib/hooks/contexts/SubsonicContext");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

const stubName = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5);

const useRemoteReceiverStorage = () => {
  const {
    subsonic,
    isLoggedIn
  } = (0, _SubsonicContext.useSubsonic)(); // consolidating into single instance

  const [remoteName, setRemoteName] = (0, _reactUse.useLocalStorage)('subsonic.subfirelib.remoteName', stubName);
  const [remoteEnabled, setRemoteEnabled] = (0, _reactUse.useLocalStorage)('subsonic.subfirelib.remoteEnabled', true);
  const [remotePlaylist, setRemotePlaylist] = (0, _react.useState)(null);
  const [remotePLComment, setRemotePLComment] = (0, _react.useState)('disabled');
  const remotePlCommentRef = (0, _react.useRef)(remotePLComment);
  const intervalRef = (0, _react.useRef)(null);
  (0, _react.useEffect)(() => {
    if (!isLoggedIn) {
      setRemotePlaylist(p => null);
      return;
    }

    ;
    const prefix = 'zz-sbr-';

    (async () => {
      let rpl = remotePlaylist; // check if this is just a rename - rename the current instead of creating new like the old days

      if (rpl) {
        if (rpl.name !== prefix + remoteName) {
          rpl = await subsonic.updatePlaylist(rpl.id, rpl.comment, false, prefix + remoteName, null, null);
          setRemotePlaylist(r => rpl);
        }

        return;
      }

      let pls = await subsonic.getPlaylists();
      let pl = pls.find(p => p.name === prefix + remoteName);
      console.log(pl);
      if (!pl) pl = await subsonic.createPlaylist(prefix + remoteName);
      pl.comment = 'pending';
      pl = await subsonic.updatePlaylist(pl.id, pl.comment, false, pl.name, null, null);
      setRemotePlaylist(p => pl);
    })();
  }, [remoteName, isLoggedIn]); // eslint-disable-line

  (0, _react.useEffect)(() => {
    if (!remoteEnabled || !remotePlaylist) {
      setRemotePLComment('disabled');
      clearInterval(intervalRef.current);
      intervalRef.current = null;
      return;
    }

    ;
    if (intervalRef.current) clearInterval(intervalRef.current);
    intervalRef.current = setInterval(() => {
      (async () => {
        const pl = await subsonic.getPlaylist(remotePlaylist.id);

        if (pl) {
          const comment = pl.comment; // console.log({ comment });
          // this function is cached so we need to use a ref to keep an eye on the current value

          if (comment !== remotePlCommentRef.current) {
            console.log('enabled?', comment);
            setRemotePLComment(c => comment);
          }
        }
      })();
    }, 1500);
    return () => {
      console.log('disabled');
      setRemotePLComment('disabled');
      clearInterval(intervalRef.current);
      intervalRef.current = null;
    };
  }, [remoteEnabled, remotePlaylist]); // eslint-disable-line

  (0, _react.useEffect)(() => {
    remotePlCommentRef.current = remotePLComment;
  }, [remotePLComment]);

  const acknowledgePLComment = () => {
    (async () => {
      let pl = remotePlaylist;
      pl.comment = 'pending';
      pl = await subsonic.updatePlaylist(pl.id, pl.comment, false, pl.name, null, null);
    })();
  };

  return {
    remotePLComment,
    acknowledgePLComment,
    remoteName,
    setRemoteName,
    remoteEnabled,
    setRemoteEnabled
  };
};

exports.useRemoteReceiverStorage = useRemoteReceiverStorage;
const RemoteReceiverContext = /*#__PURE__*/(0, _react.createContext)();
exports.RemoteReceiverContext = RemoteReceiverContext;

const RemoteReceiverProvider = ({
  children
}) => /*#__PURE__*/_react.default.createElement(RemoteReceiverContext.Provider, {
  value: useRemoteReceiverStorage()
}, children);

exports.RemoteReceiverProvider = RemoteReceiverProvider;
RemoteReceiverProvider.propTypes = {
  children: _propTypes.default.any
};

const useRemoteReceiver = () => (0, _react.useContext)(RemoteReceiverContext);

exports.useRemoteReceiver = useRemoteReceiver;
var _default = useRemoteReceiver;
exports.default = _default;