/* globals Twitch, i18n */

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

const SAVE_SUCCESS = i18n('Your cheer badges have been successfully saved');
const SAVE_ERROR = i18n('There was a problem updating your new settings. Please try again.');

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

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

  // Own properties:
  isSaving: false,
  bitsBadges: null,
  bitsBadgeTiers: null,

  tiers: computed('bitsBadgeTiers.tiers', 'bitsBadges.bits.versions', function () {
    let badgeTiers = this.get('bitsBadgeTiers.tiers');
    let badgeVersions = this.get('bitsBadges.bits.versions');

    let tiers = badgeTiers.map(badgeTier => {
      let threshold = badgeTier.threshold;
      let badgeVersion = badgeVersions[threshold];

      return {
        badge: badgeVersion.image_url_1x,
        enabled: badgeTier.enabled,
        threshold: threshold
      };
    });

    tiers.sort((a, b) => {
      return a.threshold - b.threshold;
    });

    return tiers;
  }),

  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 bits = this.get('bits');
      let userId = this.get('user._id');
      let tiers = this.get('tiers');
      let newTiers = tiers.map(tier => {
        return {
          threshold: tier.threshold,
          enabled: tier.enabled
        };
      });
      let data = { tiers: newTiers };

      this.set('isSaving', true);

      bits.setBadgeTiers(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);
      });
    }
  }
});
