"use strict";

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

var _Dispatcher = _interopRequireDefault(require("Dispatcher"));

var _RemotesActions = _interopRequireWildcard(require("subfire/actions/RemotesActions"));

var _SubsonicActions = _interopRequireDefault(require("subsonic/actions/SubsonicActions"));

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

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

const RECEIVER_INTERVAL = 5000;
const SENDER_CHECK_INTERVAL = 10000;

class RemotesStoreClass {
  constructor() {
    this.bindActions(_RemotesActions.default);
    this.bindAction(_SubsonicActions.default.RETRIEVED_PLAYLISTS, this.retrievedPlaylists); // load from local storage

    this.remoteState = _RemotesActions.RemoteStates.disabled;
    this.receivers = []; // console.warn('init', this.remoteName);
  }

  startCheckingPlaylists() {
    this.playlistsInterval = setInterval(_SubsonicActions.default.refreshPlaylists, SENDER_CHECK_INTERVAL);
  }

  enableSending([pl, source]) {
    this.sendingPlaylist = pl;
    this.f = source.fetcher;
    this.remoteState = _RemotesActions.RemoteStates.sender;
  }

  disableSending() {
    this.sendingPlaylist = null;
    this.remoteState = _RemotesActions.RemoteStates.disabled;
  }

  sendInstruction(instruction) {
    const {
      id
    } = this.sendingPlaylist;
    const f = this.f;
    f.getPlaylist(id).then(pl => {
      if (pl.playlist && pl.playlist.comment === 'pending') {
        return f.updatePlaylist(id, instruction);
      } else {
        if (pl.playlist && pl.playlist.comment !== 'pending') {
          throw "Warning: still processing previous instruction";
        }

        throw "Error: playlist no longer listening";
      }
    }).then(s => {
      console.log('should have worked...');
      return;
    }).catch(e => {
      console.error(e);

      if (e !== "Warning: still processing previous instruction") {
        this.disableSending();
      }
    });
  }

  sendRoute(route) {
    this.sendInstruction('route ' + route);

    _SubsonicActions.default.snack.defer("Remote Route sent...", {
      variant: "info"
    });
  }

  sendAction(action) {
    this.sendInstruction('action ' + action);

    _SubsonicActions.default.snack.defer("Remote Action " + action + " sent...", {
      variant: "info"
    });
  } // console.log('playlists', allPlaylists);


  retrievedPlaylists({
    allPlaylists,
    playlists,
    stations
  }) {
    this.receivers = allPlaylists.filter(pl => pl.comment === 'pending' && pl.name.startsWith('zz-sbr-') && pl.name !== 'zz-sbr-' + this.remoteName); // console.log('receivers', this.receivers);
  }

  initRemoteState([source, history]) {
    console.warn("subsonic." + window.subsonicClientName + ".remoteName", localStorage.getItem("subsonic." + window.subsonicClientName + ".remoteName"));
    this.remoteName = localStorage.getItem("subsonic." + window.subsonicClientName + ".remoteName") || Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5); // console.warn(this.remoteName);

    const remoteEnabled = localStorage.getItem("subsonic." + window.subsonicClientName + ".remoteEnabled");

    if (remoteEnabled === 'true') {
      this.enableRemoteReceiver([this.remoteName, source, history]);
    }
  }

  enableRemoteReceiver([remoteName, source, history]) {
    var that = this;
    this.remoteName = remoteName;
    this.history = history;
    localStorage.setItem("subsonic." + window.subsonicClientName + ".remoteName", remoteName);
    localStorage.setItem("subsonic." + window.subsonicClientName + ".remoteEnabled", 'true'); // TODO:[JS] react to credentials change

    const f = this.f = source.fetcher;
    const name = 'zz-sbr-' + remoteName;
    f.getPlaylists().then(pls => {
      // console.warn(pls, remoteName);
      let pl = pls.playlists.playlist.find(p => {
        // console.warn(p.name, name, p.owner, f._u);
        return p.name === name && p.owner === f._u;
      });

      if (pl) {
        // console.log('already found', pl);
        return pl;
      }

      return {};
    }).then(pl => {
      let id = pl.id;
      return f.createPlaylist(name, id);
    }).then(pl => {
      console.log('final pl', pl);
      that.id = pl.id;
      return f.updatePlaylist(that.id, 'pending');
    }).then(pl => {
      // console.log('updated');
      pl.comment = 'pending';
      that.remoteState = _RemotesActions.RemoteStates.receiver;
    }).catch(e => {
      console.error(e);
    }).then(() => {
      this.interval = setInterval(_RemotesActions.default.checkRemoteState, RECEIVER_INTERVAL);

      _SubsonicActions.default.refreshPlaylists();

      that.emitChange();
    }); // set state to RemoteStates.receiver
  }

  disableRemoteReceiver() {
    const {
      f,
      id
    } = this;
    f.deletePlaylist(id).then(s => {
      console.log('status', s);

      _SubsonicActions.default.refreshPlaylists();
    });
    this.remoteState = _RemotesActions.RemoteStates.disabled;
    localStorage.setItem("subsonic." + window.subsonicClientName + ".remoteEnabled", 'false');
    clearInterval(this.interval);
  }

  pauseRemoteReceiver() {
    const {
      f,
      id
    } = this;
    const that = this;
    clearInterval(this.interval);
    localStorage.setItem("subsonic." + window.subsonicClientName + ".remoteEnabled", 'false');
    this.remoteState = _RemotesActions.RemoteStates.receiverPaused;
    f.updatePlaylist(id, 'paused').then(s => {
      console.log('pauseRemoteReceiver', s);

      _SubsonicActions.default.refreshPlaylists();
    });
  }

  resumeRemoteReceiver() {
    const {
      f,
      id
    } = this;
    const that = this;
    this.remoteState = _RemotesActions.RemoteStates.receiver;
    f.updatePlaylist(id, 'pending').then(s => {
      console.log('resumeRemoteReceiver', s);
      that.interval = setInterval(_RemotesActions.default.checkRemoteState, RECEIVER_INTERVAL);

      _SubsonicActions.default.refreshPlaylists();
    });
  }

  checkRemoteState() {
    const {
      f,
      id,
      history
    } = this;
    f.getPlaylist(id).then(pl => {
      // console.log('checkstate pl', pl.playlist);
      const c = pl.playlist.comment || '';
      const method = history.location.pathname === '/player' ? 'replace' : 'push';
      const n = pl.playlist.name;

      if (c.startsWith('route')) {
        f.updatePlaylist(id, 'pending').then(() => {
          var r = c.substring(6);
          history[method](r);
        });
      } else if (c.startsWith('action')) {
        f.updatePlaylist(id, 'pending').then(() => {
          var a = c.substring(7);

          switch (a) {
            case 'play':
            case 'pause':
            case 'playOrPause':
            case 'playerNext':
            case 'playerPrev':
            case 'shufflePlaying':
            case 'playerSkip':
              _SubsonicActions.default[a]();

              break;

            default:
              console.warn('unexpected instruction', a);
          }
        });
      } else if (c === 'playthis') {
        // to use to basically 'cast' your current play queue over as is.  not implemented yet, needs 'bookmark' like behavior of index and position
        f.updatePlaylist(id, 'playing').then(() => {
          history[method]('/loading/playlist/' + id);
        });
      } else if (c === 'playing') {
        // this is to clear the state of the previous event.  not used.
        f.createPlaylist(n, id).then(() => {
          return f.updatePlaylist(id, 'pending');
        }).then(() => {
          console.log('playing and cleared...');
        }).catch(e => {
          console.error(e);
          this.disableRemoteReceiver();
        });
      }
    }).catch(err => {
      console.log('maybe not logged in', err);
    });
  }

}

exports.RemotesStoreClass = RemotesStoreClass;

var _default = _Dispatcher.default.createStore(RemotesStoreClass, 'RemotesStore');

exports.default = _default;