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

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

  // Passed-in properties:
  channelId: null,
  subscriberCount: null,
  closeModal: null,

  // Own properties:
  emailBody: '',
  emailTitle: '',

  hasAttemptedClosingModalWithoutSending: false,
  hasSendingEmailToSubscribersErrored: false,
  hasSentEmailToSubscribersSuccessfully: false,
  isSendingEmailToSubscribers: false,

  isSendingEmailToSubscribersDisabled: computed('emailBody', 'emailTitle', function () {
    return !this.get('emailBody') || !this.get('emailTitle');
  }),

  actions: {
    closeModal() {
      let hasAttemptedClosingModalWithoutSending = this.get('hasAttemptedClosingModalWithoutSending');
      let hasDraftedEmail = !!this.get('emailBody') || !!this.get('emailTitle');

      if (!hasAttemptedClosingModalWithoutSending && hasDraftedEmail) {
        this.set('hasAttemptedClosingModalWithoutSending', true);

        return false;
      }

      this.set('emailBody', '');
      this.set('emailTitle', '');
      this.set('hasAttemptedClosingModalWithoutSending', false);
      this.set('hasSendingEmailToSubscribersErrored', false);
      this.set('hasSentEmailToSubscribersSuccessfully', false);
      this.set('isSendingEmailToSubscribers', false);

      this.get('closeModal')();

      return true;
    },

    sendEmailToSubscribers() {
      this.set('isSendingEmailToSubscribers', true);

      let channelId = this.get('channelId');
      let api = this.get('api');
      let url = `/api/channels/${ channelId }/subscriber_emails`;
      let postData = {
        title: this.get('emailTitle'),
        body: this.get('emailBody')
      };

      let postRequest = api.request('post', url, postData);

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

        this.set('hasSentEmailToSubscribersSuccessfully', true);
      }).catch(() => {
        if (this.isDestroyed) { return; }

        this.set('hasSendingEmailToSubscribersErrored', true);
      }).finally(() => {
        if (this.isDestroyed) { return; }

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