import Component from 'ember-component';
import injectService from 'ember-service/inject';
import VodAppeal from 'web-client/models/vod-appeal';
import { libraries as lib } from 'web-client/utilities/vod-appeals-util';
import computed from 'ember-computed';
import { assert } from 'ember-metal/utils';
import getOwner from 'ember-owner/get';

/*
  Sequenced form for submitting an appeal.
  Parameters:
    Required:
      vodId
      onExit - action to perform when exiting from the form ('Appeal More Vods')
 */

// vods_controller.rb REQUIRED_VOD_APPEAL_PARAMS
let requiredVodAppealParams = [
  'track_appeals',
  'full_name',
  'street_address_1',
  'country',
  'city'
];

export default Component.extend({
  api: injectService(),
  vodAppealsService: injectService('vod-appeals'),

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

    let vodId = this.get('vodId');
    assert(`${this} requires a vodId attribute`, !!vodId);

    let vodAppeal = VodAppeal.find(getOwner(this), vodId);
    this.set('vodAppeal', vodAppeal);

    this.get('vodAppealsService').getMutedTracks(vodId).then(mutedTracks => {
      if (this.isDestroyed) { return; }
      this.set('mutedTracks', mutedTracks);
    });
  },

  /* Computed Properties */

  // Sequence/state managers
  tracksSelected: false,
  submittingAppeal: false,

  // Form Data
  tracksToAppeal: computed('mutedTracks', function () {
    let mutedTracks = this.get('mutedTracks');

    if (mutedTracks) {
      return mutedTracks.reduce(function (appealedTracks, track) {
        if (track.reasonForAppealing) {
          appealedTracks.push({
            audible_magic_response_id: track.id,
            reason: track.reasonForAppealing.reason
          });
        }
        return appealedTracks;
      }, []);
    }
  }),

  // data for creating VOD appeal, gets POST to api/vods/:vod_id/appeal
  appealData: computed(
    'tracksToAppeal', 'fullName', 'streetPrimary', 'streetSecondary',
    'city', 'province', 'zipcode', 'country',
  function () {
    return {
      track_appeals: this.get('tracksToAppeal'),
      full_name: this.get('fullName'),
      street_address_1: this.get('streetPrimary'),
      street_address_2: this.get('streetSecondary'),
      city: this.get('city'),
      zipcode: this.get('zipcode'),
      country: this.get('country')
    };
  }),

  formDataIsValid: computed('appealData', function () {
    let appealData = this.get('appealData');

    return !requiredVodAppealParams.find(function (fieldName) {
      return !appealData[fieldName];
    });
  }),

  actions: {
    onExit() {
      this.sendAction('onExit');
    },

    submitAppeal() {
      let self = this;

      if (this.get('formDataIsValid')) {
        this.set('submittingAppeal', true);
        this.get('vodAppeal').submitAppeal(this.get('appealData')).then(function () {
          self.set('submittingAppeal', false);
          self.set('submittedAppeal', true); // appeals-receipt messaging changes
        }, function () {
          lib.notify.error('Appeal submission failed.');
          self.set('submittingAppeal', false);
        });
      } else {
        lib.notify.error('Please fill out all the required fields.');
      }
    },

    selectTracks() {
      if (!this.get('vodAppeal.canCreateAppeal')) {
        return;
      }

      let mutedTracks = this.get('mutedTracks');
      let trackToAppealExists = mutedTracks.find(function (track) {
        return track.reasonForAppealing;
      });

      if (!trackToAppealExists) {
        lib.notify.error('Please select a reason for the audio you wish to appeal.');
      } else {
        this.set('tracksSelected', true);
      }
    },

    selectMoreTracks() {
      this.set('tracksSelected', false);
    }
  }
});
