/* global i18n */

import Controller from 'ember-controller';
import injectService from 'ember-service/inject';
import computed from 'ember-computed';

const TIMS_SUCCESS = 'success';
const TIMS_NO_ACTION = 'no_action';
const SAVE_SUCCESS = i18n('Streamline Bounty Agreement Changes Are Saved');
const SAVE_ERROR = i18n('Streamline Bounty Agreement Changes Failed');

export default Controller.extend({
  bounties: injectService(),
  globals: injectService(),
  notify: injectService(),

  isSaving: false,
  isStreamlineAmendmentModalOpen: false,
  isStreamlineAmendmentConfirmationModalOpen: false,
  user: computed.alias('model.user'),
  amendmentAccepted: computed.alias('model.amendmentAccepted'),

  requiresRoyaltyTaxAction: computed('model.product.royaltyTaxState', function () {
    let royaltyTaxState = this.get('model.product.royaltyTaxState');

    return royaltyTaxState !== TIMS_SUCCESS && royaltyTaxState !== TIMS_NO_ACTION;
  }),

  requiresServiceTaxAction: computed.alias('model.requiresServicesTax'),

  pendingStreamlineAmendmentPreRequisites: computed.or('requiresRoyaltyTaxAction', 'requiresServiceTaxAction'),

  _setStreamlineAmendment(accepted) {
    this.set('amendmentAccepted', accepted);
  },

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

    let notify = this.get('notify');

    this.set('isSaving', true);

    return this.get('bounties').setStreamlineAmendmentAccepted(this.get('user._id')).then(() => {
      if (this.isDestroyed) { return; }

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

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

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

  isStreamlineAmendmentDisabled: computed.or('isStreamlineAmendmentAcceptedAndSavedOrSaving', 'pendingStreamlineAmendmentPreRequisites'),

  actions: {
    syncAndOpenStreamlineAmendmentModal(isAccepted) {
      if (this.get('isStreamlineAmendmentModalOpen') || this.get('isStreamlineAmendmentConfirmationModalOpen')) { return; }

      this._setStreamlineAmendment(isAccepted);

      if (isAccepted) {
        this.set('isStreamlineAmendmentModalOpen', true);
      }
    },

    // Actions for Streamline Amendment modal
    closeStreamlineAmendmentModal(accepted) {
      if (!this.get('isStreamlineAmendmentModalOpen') || this.get('isStreamlineAmendmentConfirmationModalOpen')) { return; }

      this.set('isStreamlineAmendmentModalOpen', false);

      if (!accepted) {
        this._setStreamlineAmendment(false);
        return;
      }

      this.set('isStreamlineAmendmentConfirmationModalOpen', true);
    },

    closeStreamlineAmendmentConfirmationModal(confirmed) {
      this._setStreamlineAmendment(confirmed);
      if(confirmed) {
        this._saveStreamlineAmendment();
      }

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