/* global i18n */

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

const DELETE_SUCCESS = i18n('Subscriber badge successfully deleted');
const DELETE_FAILURE = i18n('Failed to delete subscriber badge');

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

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

  // Passed-in properties:
  badge: null,
  onBadgeDelete: null,
  channelID: null,

  // Own properties:
  isConfirmationModalOpen: false,
  isDeleting: false,

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

    let isBadgeValid = !!this.get('badge.id');
    let isOnBadgeDeleteValid = typeof this.get('onBadgeDelete') === 'function';
    let isChannelIDValid = typeof this.get('channelID') === 'number';

    assert(`${this} requires valid argument "badge"`, isBadgeValid);
    assert(`${this} requires valid argument "onBadgeDelete"`, isOnBadgeDeleteValid);
    assert(`${this} requires valid argument "channelID"`, isChannelIDValid);
  },

  actions: {
    confirm() {
      if (!this.get('isConfirmationModalOpen') || this.get('isDeleting')) { return; }

      this._deleteBadge();
    },

    closeConfirmationModal() {
      if (this.get('isDeleting')) { return; }

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

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

  _deleteBadge() {
    let subscriptions = this.get('subscriptions');
    let channelID = this.get('channelID');
    let badgeID = this.get('badge.id');
    let onBadgeDelete = this.get('onBadgeDelete');
    let notify = this.get('notify');

    this.set('isDeleting', true);

    let deleteRequest = subscriptions.deleteBadge({ channelID, badgeID });

    deleteRequest.then(deletedBadge => {
      if (this.isDestroyed) { return; }

      onBadgeDelete(deletedBadge);

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

      notify.error(DELETE_FAILURE);

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

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