"use strict";

exports.__esModule = true;
exports.default = RoutePlayerLoader;

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

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

var _reactRouterDom = require("react-router-dom");

var _hooks = require("subfirelib/hooks");

var _Loader = _interopRequireDefault(require("./Loader"));

var _utils = require("subfirelib/utils/utils");

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

// eslint-disable-line
function RoutePlayerLoader(props) {
  const {
    targetRoute,
    remoteRoute,
    testMode = false
  } = props;
  const {
    isEnabled: isRemoteEnabled,
    sendRemoteRoute
  } = (0, _hooks.useRemoteSender)();
  const params = (0, _reactRouterDom.useParams)();
  const history = (0, _reactRouterDom.useHistory)();
  const location = (0, _reactRouterDom.useLocation)();
  const {
    allPlaylists,
    stations
  } = (0, _hooks.usePlaylistsScanner)();
  const {
    subsonic,
    cache
  } = (0, _hooks.useSubsonic)();
  const {
    ArtistsById,
    Albums,
    MusicPaths
  } = cache;
  const {
    setCurrentQueue,
    setIdx
  } = (0, _hooks.useQueue)(); // eslint-disable-line

  (0, _react.useEffect)(() => {
    console.log('in RPL');
    return () => console.log('out RPL');
  });

  if (isRemoteEnabled) {
    console.log('remote', location);
    sendRemoteRoute(location.pathname);
    setTimeout(() => history.replace(remoteRoute), 10);
    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, "going to remote...");
  }

  const nomatch = () => {
    console.warn('nomatch', params);
    history.goBack();
  };

  const results = async res => {
    if (params.mode === 'shuffle' && res != null && res.entry) {
      res.entry = (0, _utils.arrayShuffle)(res.entry);
      res.entry = (0, _utils.arrayShuffle)(res.entry);
      res.entry = (0, _utils.arrayShuffle)(res.entry);
      res.entry = (0, _utils.arrayShuffle)(res.entry);
      res.entry = (0, _utils.arrayShuffle)(res.entry);
    }

    let idx = 0;
    res.current = res.current || params.bookmarkId;
    res.position = res.position || params.position;

    if (res.current && res != null && res.entry) {
      idx = res.entry.findIndex(e => e.id + '' === res.current + '');

      if (idx === -1) {
        idx = 0; // find entry and push it - shouldn't happen with play queue

        const b = cache.Bookmarks.find(b => b.entry.id === res.current);
        if (b) res.entry.unshift(b);
      }
    }

    const rule = {
      type: params.type,
      id: params.id
    }; // hack fix for 2.x

    if (rule.type === 'radiostation') rule.type = 'station';
    if (params.mode) rule.mode = params.mode; // rule.position was an overlap for bookmarks in the old system. no longer needed
    // bookmark source SubFire will be added on bookmark save, but isn't part of the rule anymore at this level

    let name = res.name || res.title;
    if (params.mode === 'radio') name += ' Radio';
    console.log({
      name,
      rule
    });
    document.querySelector('audio').autoplay = true; // dislike having to peak in like this

    setCurrentQueue((res == null ? void 0 : res.entry) || [], idx, name, rule, res.position);
    return results;
  };

  const finalize = async () => {
    if (testMode) {
      console.warn('testing/storybook', targetRoute, remoteRoute);
      return;
    }

    history.replace(targetRoute);
  };

  const rules = [{
    match: params => {
      if (params.type === 'playQueue') {
        return {
          name: 'Play Queue',
          id: -1,
          coverArt: -1
        };
      }
    },
    load: async params => {
      const pq = await subsonic.getPlayQueue();
      return {
        entry: pq.playQueue.entry,
        current: pq.playQueue.current,
        position: pq.playQueue.position,
        name: 'Play Queue'
      };
    },
    results,
    finalize
  }, {
    match: params => {
      if (params.type === 'playlist') {
        const pl = allPlaylists.find(p => p.id + '' === params.id + '');
        if (pl) return pl;
        return {
          name: 'Some Playlist',
          id: params.id,
          coverArt: 'pl-' + params.id
        };
      }

      return null;
    },
    load: async params => {
      const pl = await subsonic.getPlaylist(params.id);
      console.log('pl', pl);
      return pl;
    },
    results,
    finalize
  }, {
    match: params => {
      if (params.type === 'radiostation' || params.type === 'station') {
        const pl = stations.find(p => p.id + '' === params.id + '');
        if (pl) return pl;
      }

      return null;
    },
    load: async params => {
      const pl = stations.find(p => p.id + '' === params.id + '');
      const songs = await pl.generateAll();
      return {
        entry: songs,
        name: pl.name
      };
    },
    results,
    finalize
  }, {
    match: params => {
      if (params.type === 'artistAction' || params.type === 'artist') {
        const artist = ArtistsById[params.id];
        return artist;
      }

      return null;
    },
    load: async params => {
      let pl;

      if (params.type === 'artistAction') {
        // todo - see if this is similar songs or top songs and use that instead
        if (params.mode === 'shuffleAlbums') {
          pl = await subsonic.getArtistAlbums(params.id);
          pl.albumCollection.albums = (0, _utils.arrayShuffle)(pl.albumCollection.albums);
          pl.albumCollection.albums = (0, _utils.arrayShuffle)(pl.albumCollection.albums);
          pl.albumCollection.albums = (0, _utils.arrayShuffle)(pl.albumCollection.albums);
          pl.albumCollection.albums = (0, _utils.arrayShuffle)(pl.albumCollection.albums);
          pl.albumCollection.albums = (0, _utils.arrayShuffle)(pl.albumCollection.albums);
          pl.albumCollection = {
            song: pl.albumCollection.albums.flat()
          };
        } else if (params.mode === 'radio') {
          pl = await subsonic.getTopSimilarSongs(params.id, 200, 0);
          console.log(pl);
          pl = (0, _utils.arrayShuffle)(pl);
          pl = (0, _utils.arrayShuffle)(pl);
          pl = (0, _utils.arrayShuffle)(pl);
          pl = (0, _utils.arrayShuffle)(pl);
          pl = (0, _utils.arrayShuffle)(pl);
          pl = {
            albumCollection: {
              song: pl || []
            }
          };
        } else if (params.mode === 'top') {
          pl = await subsonic.getTopArtistSongs(params.id);
          pl.albumCollection = pl.topSongs || {
            song: []
          };
        } else {
          pl = await subsonic.getArtistSongs(params.id);
        }

        console.log('pl', pl);
        return {
          entry: pl.albumCollection.song,
          name: ArtistsById[params.id].name
        };
      }
    },
    results,
    finalize
  }, {
    match: params => {
      if (params.type === 'albumAction' || params.type === 'album') {
        const id = params.id;
        const album = Albums[id] || {
          name: '_loading_',
          id: id,
          coverArt: 'al-' + id
        };
        return album;
      }

      return null;
    },
    load: async params => {
      let pl;

      if (params.type === 'albumAction') {
        // todo - see if this is similar songs or top songs and use that instead
        pl = await subsonic.getAlbum(params.id);
        return {
          entry: pl.song,
          name: pl.name || pl.title
        };
      }
    },
    results,
    finalize
  }, {
    match: params => {
      if (params.type === 'directoryAction' || params.type === 'directory') {
        let pl = MusicPaths[params.id];
        if (pl) return pl;
        return {
          name: 'Loading...',
          id: params.id,
          coverArt: params.id
        };
      }

      return null;
    },
    load: async params => {
      let pl;

      if (params.type === 'directoryAction') {
        // todo - see if this is similar songs or top songs and use that instead
        if (params.mode === 'shuffleAlbums') {
          pl = await subsonic.getMusicDirectoryAlbums(params.id);
          pl.musicDirectoryAlbums.album = (0, _utils.arrayShuffle)(pl.musicDirectoryAlbums.album);
          pl.musicDirectoryAlbums.album = (0, _utils.arrayShuffle)(pl.musicDirectoryAlbums.album);
          pl.musicDirectoryAlbums.album = (0, _utils.arrayShuffle)(pl.musicDirectoryAlbums.album);
          pl.musicDirectoryAlbums.album = (0, _utils.arrayShuffle)(pl.musicDirectoryAlbums.album);
          pl.musicDirectoryAlbums.album = (0, _utils.arrayShuffle)(pl.musicDirectoryAlbums.album);
          pl.musicDirectory = {
            song: pl.musicDirectoryAlbums.album.flat()
          };
        } else if (params.mode === 'radio') {
          pl = await subsonic.getTopSimilarSongs(params.id, 200, 0);
          console.log(pl);
          pl = (0, _utils.arrayShuffle)(pl);
          pl = (0, _utils.arrayShuffle)(pl);
          pl = (0, _utils.arrayShuffle)(pl);
          pl = (0, _utils.arrayShuffle)(pl);
          pl = (0, _utils.arrayShuffle)(pl);
          pl = {
            musicDirectory: {
              song: pl || []
            }
          };
        } else {
          pl = await subsonic.getMusicDirectorySongs(params.id);
        }

        console.log('pl', pl);
        return {
          entry: pl.musicDirectory.song,
          name: MusicPaths[params.id].name
        };
      }
    },
    results,
    finalize
  }, {
    match: params => {
      if (params.type === 'song') {
        return {
          name: 'Loading Song',
          id: params.id,
          coverArt: params.id
        };
      }

      return null;
    },
    load: async params => {
      console.log(params);
      const song = await subsonic.getSong(params.id);
      return {
        entry: [song],
        name: song.name || song.title
      };
    },
    results,
    finalize
  }];
  return /*#__PURE__*/_react.default.createElement(_Loader.default, {
    rules: rules,
    params: params,
    nomatch: nomatch,
    pathname: location.pathname
  });
}

RoutePlayerLoader.propTypes = {
  type: _propTypes.default.string,
  id: _propTypes.default.number,
  targetRoute: _propTypes.default.string,
  remoteRoute: _propTypes.default.string,
  testMode: _propTypes.default.bool
};