/* globals Twitch */
import Component from 'ember-component';
import computed from 'ember-computed';
import Ember from 'ember';
import { htmlSafe } from 'ember-string';

import { uploadData } from 'web-client/utilities/upload-form-data';

const ERROR_FILE_TOO_LARGE = 'File too large.';
const ERROR_FILE_WRONG_TYPE = 'Incompatible format. File must be an image.';
const ERROR_FILE_OTHER = 'Upload error';
const FILE_ACCEPTED_TYPES = '^image/';
const FILE_MAX_SIZE = 3000000;

const { Handlebars } = Ember;
const { escapeExpression } = Handlebars.Utils;

export default Component.extend({
  uploadImageTemplate: 'shared/upload-image',
  channel: null,
  showRecommendedSize:  true,

  bannerStyle: computed('channel.profileBanner', function () {
    return htmlSafe(`background-image: url(${ escapeExpression(this.get('channel.profileBanner')) });`);
  }),

  _checkFile(file) {
    if (!file.type.match(FILE_ACCEPTED_TYPES)) {
      this.set('errorMessage', ERROR_FILE_WRONG_TYPE);
      this.set('isLoading', false);
      return false;
    }
    if (file.size > FILE_MAX_SIZE) {
      this.set('errorMessage', ERROR_FILE_TOO_LARGE);
      this.set('isLoading', false);
      return false;
    }
    return true;
  },

  actions: {
    onFileDrop(file) {
      this.set('isLoading', true);
      this.set('errorMessage', '');

      if (this._checkFile(file)) {
        let url = Twitch.uri.profileBanner(this.get('channel.id'));
        return uploadData({ url, data: {'files[]': file} }).then(() => {
          return this.get('channel').reload();
        }).then(() => {
          this.get('closeModal')();
        }, xhr => {
          if (xhr.target && xhr.target.status & xhr.target.status === 413) {
            this.set('errorMessage', ERROR_FILE_TOO_LARGE);
          } else {
            this.set('errorMessage', ERROR_FILE_OTHER);
          }
        }).finally(() => {
          this.set('isLoading', false);
        });
      }
    },

    removeBanner() {
      this.set('channel.profileBanner', null);

      let url = Twitch.uri.profileBanner(this.get('channel.id'));
      return uploadData({ url, data: {clear_image: true} }).then(() => {
        return this.get('channel').reload();
      }).catch(() => {
        this.get('channel').rollbackAttributes();
      });
    }
  }
});
