import Route from 'ember-route';
import injectService from 'ember-service/inject';
import RSVP from 'rsvp';
import { assign } from 'ember-platform';

const IN_PROGRESS_STATUS = 'pending_transcode,transcoding,failed';
const PROCESSED_STATUS = 'recorded';
const PROCESSED_LIMIT = 40;

export default Route.extend({
  videoProcessor: injectService(),
  session: injectService(),

  model() {
    let channelName = this.modelFor('user').get('id');

    // Return early if the user's email isn't verified.
    if (!this.modelFor('manager').get('emailVerified')) {
      return modelWith({ isVerified: false });
    }

    // Perform a query that returns _all_ in-progress videos, but only the
    // first set of results for processed videos.
    return RSVP.all([
      this.get('store').query('manager/uploader-video', {
        channelName,
        status: IN_PROGRESS_STATUS
      }),

      this._queryProcessedVideos()
    ]).then(([inProgressVideos]) => {
      return modelWith({
        videos: this.get('store').peekAll('manager/uploader-video'),
        inProgressVideos,
        channelName
      });
    }).catch((error) => {
      if (error.status) {
        return modelWith({ error });
      }

      throw error;
    });
  },

  afterModel({ inProgressVideos }) {
    this._super(...arguments);
    this.get('videoProcessor').pushRecordArray(inProgressVideos);
  },

  activate() {
    this.controllerFor('manager').set('activeUploadsTab', true);
  },

  deactivate() {
    this.get('videoProcessor').clear();
    this.controllerFor('manager').set('activeUploadsTab', false);
  },

  _queryProcessedVideos(offset = 0) {
    let channelName = this.modelFor('user').get('id');

    return this.get('store').query('manager/uploader-video', {
      channelName,
      status: PROCESSED_STATUS,
      limit: PROCESSED_LIMIT,
      offset: offset
    });
  },

  actions: {
    loadMoreProcessedVideos(offset) {
      return this._queryProcessedVideos(offset);
    }
  }
});

function modelWith(obj) {
  return assign({
    videos: [],
    inProgressVideos: [],
    channelName: null,
    isVerified: true,
    error: null
  }, obj);
}
