/* globals Twitch, i18n */

import Component from 'ember-component';
import injectService from 'ember-service/inject';

const MINIMUM_REQUIREMENT_ERROR = i18n('Minimum Single Bit setting must be less than or equal to Minimum Total Bits.');
const SAVE_SUCCESS = i18n('Your bits settings have been successfully saved. It may take a few minutes for your settings to take effect.');
const SAVE_ERROR = i18n('There was a problem updating your new settings. Please try again.');

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

  // Property set by the route:
  user: null,

  // Own properties:
  isSaving: false,
  minBits: null,
  minBitsEmote: null,

  actions: {
    // saving-button requires an action to be defined or it will throw an exception.
    // The save button action will be a no-op, and the button is marked as type="submit".
    // The save() action is defined as the action for the form.
    noop() {},

    save() {
      if (this.get('isSaving')) { return; }

      let minBits = parseInt(this.get('minBits'), 10);
      let minBitsEmote = parseInt(this.get('minBitsEmote'), 10);

      if (minBitsEmote > minBits) {
        return Twitch.notify.error(MINIMUM_REQUIREMENT_ERROR);
      }

      let bits = this.get('bits');
      let userId = this.get('user._id');
      let data = {
        min_bits: minBits,
        min_bits_emote: minBitsEmote
      };

      this.set('isSaving', true);

      bits.setChannelSettings(userId, data).then(() => {
        if (this.isDestroyed) { return; }

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

        Twitch.notify.error(SAVE_ERROR);
      }).finally(() => {
        if (this.isDestroyed) { return; }

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