"use strict";

exports.__esModule = true;
exports.useSubsonic = exports.SubsonicProvider = exports.SubsonicContext = void 0;

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

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

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

var _api = require("subfirelib/api");

var _CredentialsContext = require("subfirelib/hooks/contexts/CredentialsContext");

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 SubsonicContext = /*#__PURE__*/(0, _react.createContext)();
exports.SubsonicContext = SubsonicContext;

const SubsonicProvider = ({
  children,
  clientName,
  embeddedCredentials
}) => {
  const value = (0, _CredentialsContext.useCredentials)();
  const [current] = embeddedCredentials ? [embeddedCredentials] : value; // storing the folder - eventually i want to move this to a subfire prefix

  const [musicFolderId, setMusicFolderId] = (0, _reactUse.useLocalStorage)('initMusicFolder', '-1'); // establishing that the user is logged in and the actual folder's limited data is loaded.

  const [loginState, setLoginState] = (0, _react.useState)(false);
  const [musicFolderLoaded, setMusicFolderLoaded] = (0, _react.useState)(false);

  const tryAgain = () => {
    setLoginState(_api.loginStates.notLoggedIn);
    const s = _api.Subsonic;
    const {
      server,
      username,
      password,
      bitrate
    } = current;
    s.open(server, username, password, bitrate, clientName).then(res => {
      setLoginState(_api.loginStates.partiallyLoggedIn);
    }).then(s.getMusicFolders).then(res => {}).then(s.getIndexes).then(res => {}).then(s.getArtists).then(res => {}).then(s.getGenres).then(() => {
      // console.log('done');
      setLoginState(_api.loginStates.fullyLoggedIn);
    }).catch(rej => {
      console.log(rej);
    });
  };

  const loadFolderIds = () => {
    if (!loginState === _api.loginStates.fullyLoggedIn) return;

    async function doLoadFolderIds() {
      setMusicFolderLoaded(false);
      await _api.Subsonic.getIndexes(musicFolderId);
      await _api.Subsonic.getArtists(musicFolderId);
      setMusicFolderLoaded(true);
    }

    doLoadFolderIds();
  };

  (0, _react.useEffect)(tryAgain, [current, clientName]);
  (0, _react.useEffect)(loadFolderIds, [loginState, musicFolderId]); // for bookmark rendering

  const getObject = (type, id) => {
    switch (type) {
      case 'playlist':
      case 'station':
        const p = _api.SubsonicCache.Playlists.find(x => {
          return x.id === id;
        });

        return Promise.resolve(p);

      case 'albumID3':
      case 'albumAction':
        return _api.Subsonic.getAlbum(id);

      case 'artist':
      case 'artistAction':
        return _api.Subsonic.getArtist(id);

      case 'album':
      case 'directory':
      case 'directoryAction':
        return _api.Subsonic.getMusicDirectory(id);

      case 'folderShuffle':
        const mf = id === -1 ? {
          name: 'All Music Folders',
          id: -1
        } : _api.SubsonicCache.MusicFolders.find(x => x.id + '' === id + '');
        return Promise.resolve(mf);

      case 'playQueue':
        return Promise.resolve({
          name: 'Play Queue',
          id: -1
        });

      case 'podcasts':
        return Promise.resolve({
          name: 'Podcasts',
          id: -1
        });

      case 'song':
        return _api.Subsonic.getSong(id);

      default:
        return Promise.resolve({
          name: 'Unsupported Type',
          id: -1
        });
    }
  };

  const properties = {
    subsonic: _api.Subsonic,
    cache: _api.SubsonicCache,
    loginState,
    isLoggedIn: loginState === _api.loginStates.fullyLoggedIn,
    musicFolderLoaded,
    musicFolderId,
    tryAgain,
    setMusicFolderId,
    getObject
  };
  return /*#__PURE__*/_react.default.createElement(SubsonicContext.Provider, {
    value: properties
  }, children);
};

exports.SubsonicProvider = SubsonicProvider;
SubsonicProvider.propTypes = {
  children: _propTypes.default.any,
  clientName: _propTypes.default.string,
  embeddedCredentials: _propTypes.default.object
};

const useSubsonic = () => (0, _react.useContext)(SubsonicContext);

exports.useSubsonic = useSubsonic;