import Service from 'ember-service';
import Map from 'ember-map';
import injectService from 'ember-service/inject';
import RSVP from 'rsvp';

const CONCURRENT_DOWNLOAD_LIMIT = 3;

export default Service.extend({
  api: injectService(),
  currentDownloads: Map.create(),
  downloadLimit: CONCURRENT_DOWNLOAD_LIMIT,

  fetchDownload(videoID) {
    // HACK: backend should be returning rate_limited status
    let currentDownloads = this.get('currentDownloads');

    if (!currentDownloads.has(videoID) && currentDownloads.size >= this.get('downloadLimit')) {
      return RSVP.resolve({status: 'rate_limited'});
    }
    currentDownloads.set(videoID, true);
    // HACK

    let url = `/kraken/vods/${videoID}/download`;
    return this.get('api').authRequest('get', url).then((response) => {
      if (response.status === 'complete' || response.status === 'failed') {
        this.finishedDownload(videoID);
      }
      return response;
    }, (response) => {
      this.finishedDownload(videoID);
      return RSVP.reject(response);
    });
  },

  finishedDownload(videoID) {
    let currentDownloads = this.get('currentDownloads');
    currentDownloads.delete(videoID);
  }
});
