/* globals i18n */

import $ from 'jquery';
import Route from 'ember-route';
import injectService from 'ember-service/inject';
import VideoManagerProperties from 'web-client/models/video-manager-properties';
import validateVideoFile from 'web-client/utilities/video-uploader/validate-video-file';

export default Route.extend({
  session: injectService(),
  headData: injectService(),
  layout: injectService(),
  videoProcessor: injectService(),
  notify: injectService(),
  navigation: injectService(),

  ttLocation: 'video_manager',

  model() {
    if (this.get('session.isAuthenticated')) {
      let userId = this.modelFor('user').id;
      return VideoManagerProperties.findOne(userId).load(true).then(
        (properties) => properties,
        (err) => err
      );
    }
  },

  buildPageTitle() {
    return { title: i18n('Video Manager') };
  },

  setupController(controller, model) {
    this._super(...arguments);

    if (model && model.get('can_create_offline_playlist') === true) {
      controller.set('canCreateOfflinePlaylist', true);
      this.set('layout.showRightColumn', true);
    }

    this.get('navigation').setSelected('Manager');
  },

  activate() {
    if (!this.get('session.isAuthenticated')) {
      $.login({ mpSourceAction: 'page-requires-login' });
    }
  },

  actions: {
    // Warn the user if they leave the video manager with pending uploads.
    willTransition(transition) {
      if (this.get('videoProcessor.hasPendingUploads') &&
          transition.isExiting('manager') &&
          !transition.data.isConfirmed
      ) {
        transition.abort();
        this.controller.set('transitionPendingConfirmation', transition);
      } else {
        this._super(...arguments);
      }
    },

    showSchedulingModal(file) {
      let errorMessage = validateVideoFile(file);
      if (errorMessage) {
        this.get('notify').error(i18n(errorMessage));
        return;
      }

      this.get('controller').showSchedulingModal(file);
    }
  }
});
