/* globals Twitch, _, i18n */

import Component from 'ember-component';
import ChatIconUploadMixin from 'web-client/mixins/chat-icon-upload';
import computed from 'ember-computed';
import run from 'ember-runloop';
import { camelize } from 'ember-string';

export default Component.extend(ChatIconUploadMixin, {
  tagName: 'form',
  attributeBindings: ['action'],
  isSaving: false,
  emoticonSet: computed.readOnly('content.emoticonSet'),

  action: computed('channel', function () {
    return `${Twitch.api.config.baseUrl}/api/ticket_products/${this.get('channel')}/submit_emoticon`;
  }),

  keyDown(e) {
    // Disable space key
    if (e.which === 32) {
      return false;
    }
  },

  input() {
    this._capitalizePreviewString();
  },

  _capitalizePreviewString: function () {
    let el = this.$(),
        code = el.find('.js-code-input').val();
    el.find('.js-code-input').val(Twitch.display.capitalize(code));
    el.find('.emoticon-code-preview .code').html(Twitch.display.capitalize(code));
  },

  submit(e) {
    e.preventDefault();
    e.stopPropagation();
    if (!this.$('.js-small').attr('value') || !this.$('.js-medium').attr('value') || !this.$('.js-large').attr('value')) {
      Twitch.notify.error(i18n("Please upload 3 images for your emoticon"));
      return;
    }
    if (!this.$().find('.js-code-input').val()) {
      Twitch.notify.error(i18n("Please input a unique code for your emoticon"));
      return;
    }
    if (!this.$('.js-code-input').val().match(/^[0-9a-zA-Z]+$/)) {
      Twitch.notify.error(i18n("Invalid entry. Please confine your expression to the characters A-Z and 0-9."));
      return;
    }

    this.set('isSaving', true);
    this.$().twitchFileUpload('send', {fileInput: this.$().find('input[type="file"]')})
    .then((data) => {
      run(() => {
        _.each(data, (value, key) => {
          this.get('content').set(camelize(key), value);
        });
        this.set('isSaving', false);
      });
      this.$().get(0).reset();
      this._capitalizePreviewString();
      Twitch.notify.success(i18n("Your emoticon has been submitted"));
    }).fail((response) => {
      run(() => {
        this.set('isSaving', false);
      });
      Twitch.notify.error(JSON.parse(response.responseText).message);
    });
  }
});
