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

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

  // passed in properties
  channdelId: null,

  // internal properties
  hasTeespringCampaign: false,
  teespringCampaigns: null,

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

    let channelId = this.get('channelId');
    let teespringUrl = `/api/channels/${ channelId }/teespring_campaigns`;

    this.get('api').request('get', teespringUrl)
      .then(response => {
        if (this.isDestroyed) { return; }

        // Revenue is returned in cents, convert to dollars
        for (let i = 0; i < response.length; i++) {
          response[i].revenue /= 100;
        }

        if (response.length > 0) {
          this.set('hasTeespringCampaign', true);
        }

        this.set('teespringCampaigns', response);
      });
  },

  totalRevenue: computed('teespringCampaigns', function() {
    let teespringCampaigns = this.get('teespringCampaigns');
    let total = 0;

    if (!teespringCampaigns) {
      return total;
    }

    for (let i = 0; i < teespringCampaigns.length; i++) {
      total += teespringCampaigns[i].revenue;
    }

    return total;
  })
});
