/* globals i18n */
import Service from 'ember-service';
import VideoPoller, { WorkItem } from 'web-client/utilities/video-uploader/video-poller';
import BeforeUnloadGuard from 'web-client/utilities/video-uploader/before-unload-guard';
import computed from 'ember-computed';

const UNLOAD_WARNING = i18n('If you leave, any current uploads will be canceled.');

export default Service.extend({
  init() {
    this._super(...arguments);
    this.unfinalizedVideos = [];
    this.isPaused = false;
    this._taskBacklog = [];
    this.videoPoller = new VideoPoller((fn, time) => this._handleTask(fn, time));
    this.beforeUnloadGuard = new BeforeUnloadGuard(window, UNLOAD_WARNING);
  },

  willDestroy() {
    this.beforeUnloadGuard.teardown();
    this._super(...arguments);
  },

  _handleTask(fn, time) {
    if (this.isPaused) {
      this._taskBacklog.push(fn);
    } else {
      this.runTask(fn, time);
    }
  },

  flushTaskBacklog() {
    this._taskBacklog.forEach((fn) => fn());
  },

  startVideoUpload(video, file) {
    let videoUpload = video.get('videoUpload');
    videoUpload.set('file', file);

    let upload = videoUpload.save();
    this.beforeUnloadGuard.trackPromise(upload);
    this.unfinalizedVideos.pushObject(video);

    return upload.then(() => {
      this.videoPoller.push(new WorkItem(video));
    });
  },

  pushRecordArray(videos) {
    let workItems = videos.map((v) => new WorkItem(v));
    this.videoPoller.push(...workItems);
  },

  clear() {
    this.videoPoller.clear();
  },

  hasPendingUploads: computed(function() {
    return this.beforeUnloadGuard.hasPendingPromises;
  }).volatile()
});
