import Component from 'ember-component';
import injectService from 'ember-service/inject';
import titleizeFilename from 'web-client/utilities/video-uploader/titleize-filename';
import extractResponseErrorMessage from 'web-client/utilities/extract-response-error-message';
import { UPLOAD_TYPE_PARAM } from 'web-client/utilities/video/types';

const TITLE_MAX_LENGTH = 100;

export default Component.extend({
  store: injectService(),

  errorMessage: null,
  video: null,
  onCancel() {},
  onEdit() {},
  onSubmit() {},

  init() {
    this._super(...arguments);

    let channelName = this.get('channelName');
    let title = titleizeFilename(this.get('file.name'), { maxLength: TITLE_MAX_LENGTH });
    let video = this.get('store').createRecord('manager/uploader-video', { channelName, title, type: UPLOAD_TYPE_PARAM });

    this.set('video', video);
  },

  willDestroyElement() {
    let video = this.get('video');

    if (video.get('isNew')) {
      video.deleteRecord();
    }

    this._super(...arguments);
  },

  actions: {
    cancel() {
      this.get('onCancel')();
    },

    uploadEdit() {
      let file = this.get('file');

      this.get('video').save().then((video) => {
        this.get('onSubmit')(video, file);
      }, (response) => {
        let message = extractResponseErrorMessage(response);
        if (message) {
          this.set('errorMessage', message);
        } else {
          throw response;
        }
      });
    }
  }
});
