import get from 'ember-metal/get';
import Component from 'ember-component';
import uploadThumbnail from 'web-client/utilities/upload-form-data';
import extractResponseErrorMessage from 'web-client/utilities/extract-response-error-message';
import RSVP from 'rsvp';
import computed from 'ember-computed';
import run from 'ember-runloop';
import { UPLOAD_TYPE_PARAM } from 'web-client/utilities/video/types';
import {
  IMAGE_TYPE_ERROR,
  ACCEPTED_FILE_TYPES
} from 'web-client/components/video/edit-modal/component';

export default Component.extend({
  classNames: ['card'],
  attributeBindings: ['data-test-video-form'],
  'data-test-video-form': true,
  acceptMimeType: ACCEPTED_FILE_TYPES.join(','),

  // Injected actions
  uploadThumbnail,
  onComplete() {},
  // Since the upload form is shared by the video manager and the vod page,
  // we need to differentiate between the two to determine whether we should
  // show publishing settings.
  inVideoManager: true,
  showPublishSettings: computed('video.type', 'inVideoManager', function() {
    return this.get('inVideoManager') && this.get('video.type') === UPLOAD_TYPE_PARAM;
  }),

  init() {
    this._super(...arguments);
    this.cropCoordinates = {};
    this.thumbnailFileToUpload = null;
  },

  // Show generated then the custom thumbnails
  thumbnailSorting: ['type:desc'],
  sortedThumbnails: computed.sort('video.thumbnails', 'thumbnailSorting'),

  _resetThumbnailFileToUpload() {
    this.set('cropCoordinates', {});
    this.set('thumbnailFileToUpload', null);
  },

  actions: {
    highlightText(event = {}) {
      let $element = event.target;
      if ($element) {
        $element.focus();
        // https://bugs.webkit.org/show_bug.cgi?id=22691
        run.next(() => $element.select());
      }
    },

    setPublishable(publishStrategy = {}) {
      let value = get(publishStrategy, 'value');
      let isPublishable = value !== 'private';

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

    selectThumbnail(thumbnail) {
      this.get('video').selectThumbnail(thumbnail);
      this._resetThumbnailFileToUpload();
    },

    removeCustomThumbnail() {
      this.get('video').removeCustomThumbnail();
    },

    setThumbnailFileToUpload(thumbnailFile) {
      if (ACCEPTED_FILE_TYPES.includes(thumbnailFile.type)) {
        this.get('video').clearThumbnailSelection();
        this.set('thumbnailFileToUpload', thumbnailFile);
        this.set('errorMessage', null);
      } else {
        this.set('errorMessage', IMAGE_TYPE_ERROR);
      }
    },

    clearThumbnailFileToUpload() {
      this.get('video').selectThumbnail(this.get('sortedThumbnails.firstObject'));
      this._resetThumbnailFileToUpload();
    },

    save() {
      let promise = RSVP.resolve();
      let thumbnail = this.get('thumbnailFileToUpload');

      promise.then(() => {
        if (!thumbnail) {
          return;
        }

        return this.uploadThumbnail({
          videoId: this.get('video.id'),
          file: thumbnail,
          data: this.get('cropCoordinates')
        });
      }).then(() => {
        return this.get('video').save();
      }).then(() => {
        return this.get('onComplete')();
      }).catch((response) => {
        let errorMessage = extractResponseErrorMessage(response);

        if (errorMessage) {
          this.set('errorMessage', errorMessage);
        } else {
          throw response;
        }
      });
    }
  },

  willDestroy() {
    this._super(...arguments);
    this.get('video').rollbackAttributes();
  }
});
