/* global i18n */

import Component from 'ember-component';
import injectService from 'ember-service/inject';
import computed from 'ember-computed';
import { assert } from 'ember-metal/utils';

export const FILE_SIZE_LIMIT_BYTES = 25000; // 25 KB

const SAVE_SUCCESS = i18n('Badge images successfully saved');
const SAVE_FAILURE = i18n('Failed to save badge images');

export default Component.extend({
  // TODO: replace <fieldset> tag with <div>:
  tagName: 'fieldset',

  notify: injectService(),
  subscriptions: injectService(),

  // Passed-in properties:
  onBadgeCreate: null,
  channelID: null,
  requiredTenureMonths: null,

  // Own properties:
  fileSizeLimitBytes: FILE_SIZE_LIMIT_BYTES,
  isConfirmationModalOpen: false,
  isSaving: false,
  image1xFile: null,
  image2xFile: null,
  image4xFile: null,

  fileSizeLimitKilobytes: computed('fileSizeLimitBytes', function () {
    let fileSizeLimitBytes = this.get('fileSizeLimitBytes');

    return Math.floor(fileSizeLimitBytes / 1000);
  }),

  isFormComplete: computed.and('image1xFile', 'image2xFile', 'image4xFile'),

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

    let isRequiredTenureMonthsValid = typeof this.get('requiredTenureMonths') === 'number';
    let isOnBadgeCreateValid = typeof this.get('onBadgeCreate') === 'function';
    let isChannelIDValid = typeof this.get('channelID') === 'number';

    assert(`${this} requires valid argument "onBadgeCreate"`, isOnBadgeCreateValid);
    assert(`${this} requires valid argument "channelID"`, isChannelIDValid);
    assert(`${this} requires valid argument "requiredTenureMonths"`, isRequiredTenureMonthsValid);

    this._lastRequiredTenureMonths = this.get('requiredTenureMonths');
  },

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

    if (this.get('requiredTenureMonths') !== this._lastRequiredTenureMonths) {
      this._resetFiles();
    }
  },

  actions: {
    confirm() {
      if (this.get('isSaving')) { return; }

      this._createBadge();
    },

    closeConfirmationModal() {
      this.set('isConfirmationModalOpen', false);
    },

    openConfirmationModal() {
      this.set('isConfirmationModalOpen', true);
    }
  },

  _generateFormData() {
    let requiredTenureMonths = this.get('requiredTenureMonths');
    let image1xFile = this.get('image1xFile');
    let image2xFile = this.get('image2xFile');
    let image4xFile = this.get('image4xFile');
    let formData = new FormData();

    formData.append('required_tenure_months', requiredTenureMonths);
    formData.append('image_1x', image1xFile);
    formData.append('image_2x', image2xFile);
    formData.append('image_4x', image4xFile);

    return formData;
  },

  _createBadge() {
    let subscriptions = this.get('subscriptions');
    let channelID = this.get('channelID');
    let formData = this._generateFormData();
    let onBadgeCreate = this.get('onBadgeCreate');
    let notify = this.get('notify');

    this.set('isSaving', true);

    let createRequest = subscriptions.createBadge({ channelID, formData });

    createRequest.then(createdBadge => {
      if (this.isDestroyed) { return; }

      onBadgeCreate(createdBadge);

      notify.success(SAVE_SUCCESS);
    }, error => {
      if (this.isDestroyed) { return; }

      notify.error(SAVE_FAILURE);

      throw error;
    }).finally(() => {
      if (this.isDestroyed) { return; }

      this.set('isSaving', false);
      this.set('isConfirmationModalOpen', false);
    });
  },

  _resetFiles() {
    this.set('image1xFile', null);
    this.set('image2xFile', null);
    this.set('image4xFile', null);
  }
});
