"use strict";

require("core-js/modules/es.array.unscopables.flat.js");

require("core-js/modules/es.promise.js");

require("core-js/modules/es.string.replace.js");

Object.defineProperty(exports, "__esModule", {
  value: 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() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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,
    testMode = false
  } = props;
  const params = (0, _reactRouterDom.useParams)();
  const history = (0, _reactRouterDom.useHistory)();
  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

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

  const results = async res => {
    if (params.mode === 'shuffle' && res !== null && res !== void 0 && 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 !== void 0 && 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
    };
    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
    });
    setCurrentQueue((res === null || res === void 0 ? void 0 : res.entry) || [], idx, name, rule, res.position);
    return results;
  };

  const finalize = async () => {
    if (testMode) {
      console.warn('testing/storybook', targetRoute);
      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.getTopSongs(ArtistsById[params.id].name);
          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
  }];
  return /*#__PURE__*/_react.default.createElement(_Loader.default, {
    rules: rules,
    params: params,
    nomatch: nomatch
  });
}

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