/* globals Twitch */
import Service from 'ember-service';
import injectService from 'ember-service/inject';
import RSVP from 'rsvp';

const MINUTE = 60000;

export default Service.extend({
  api: injectService(),
  store: injectService(),

  init() {
    this._super(...arguments);
    this._watchNowStreamsPromise = null;
    this._watchNowStreamsValidUntilTimestamp = 0;
  },

  getWatchNowStreams() {
    if (this._watchNowStreamsPromise) {
      if (this._watchNowStreamsPromise.isPending || Date.now() <= this._watchNowStreamsValidUntilTimestamp) {
        return this._watchNowStreamsPromise;
      }
    }

    this._watchNowStreamsValidUntilTimestamp = 0;
    this._watchNowStreamsPromise = this._getWatchNowStreams().then((response) => {
      this._watchNowStreamsValidUntilTimestamp = Date.now() + (5 * MINUTE);
      return response;
    });
    return this._watchNowStreamsPromise;
  },

  _getWatchNowStreams() {
    return new RSVP.Promise((resolve, reject) => {
      this.get('store').findAll('watched-channel').then((channels) => {
        let watched = [];
        channels.forEach((channel) => {
          let timestamp = channel.get('timestamp');
          if (timestamp) {
            watched.push({
              channel_id: channel.get('_id'),
              channel: channel.get('id'),
              watched_at: timestamp.toISOString()
            });
          }
        });

        let params = {
          request: {
            language: Twitch.receivedLanguage,
            watched: watched
          }
        };
        let opts = {
          version: 5,
          headers: {
            'Content-Type': 'application/json'
          }
        };
        return this.get('api').authRequest('post', '/kraken/streams/watch-now', JSON.stringify(params), opts).then(resolve, reject);
      }, reject);
    });
  }
});
