/* globals Twitch */

import Service from 'ember-service';
import injectService from 'ember-service/inject';
import computed from 'ember-computed';
import RSVP from 'rsvp';
import { ARCHIVE_TYPE_PARAM } from 'web-client/utilities/video/types';

export default Service.extend({
  api: injectService(),
  // NOTICE: The login service is deprecated, plesase use the session service.
  // See app/services/SESSION.md for more details.
  login: injectService(),
  isLoggedIn: computed.readOnly('login.isLoggedIn'),
  _resumeTimesPromise: null,

  clearResumeTimes() {
    this._resumeTimesPromise = null;
  },

  _fetchResumeTimes() {
    return this.get('login').fetchUserData(false).then(() => {
      let userId = this.get('login.userData.id');
      let url = `/api/resumewatching/user?id=${userId}`;
      return this.get('api').request('get', url);
    }).then((response) => {
      return response.videos;
    });
  },

  getResumeTime(id, broadcastId, broadcastType) {
    let isLoggedIn = this.get('isLoggedIn');
    if (isLoggedIn) {
      if (!this._resumeTimesPromise) {
        this._resumeTimesPromise = this._fetchResumeTimes();
      }
      return this._resumeTimesPromise.then((videos) => {
        if (this.isDestroyed) { return; }
          let resumeTime = videos.find(video => video.video_id === id || video.video_id === `${broadcastId}`);
          return resumeTime ? resumeTime.position : null;
      });
    }

    let vodResumeTimes = Twitch.storage.getObject('vodResumeTimes');
    let livestreamResumeTimes = Twitch.storage.getObject('livestreamResumeTimes');
    if (vodResumeTimes && vodResumeTimes[id]) {
      return RSVP.resolve(vodResumeTimes[id]);
    }
    else if (broadcastType === ARCHIVE_TYPE_PARAM && livestreamResumeTimes && livestreamResumeTimes[broadcastId]) {
      return RSVP.resolve(livestreamResumeTimes[broadcastId]);
    }
    return RSVP.resolve(null);
  }
});
