/* globals i18n */

import Component from 'ember-component';
import TicketModel from 'web-client/models/ticket';
import computed from 'ember-computed';
import injectService from 'ember-service/inject';
import $ from 'jquery';

const primePaymentProvider = 'samus';
const monthlyTicketPeriod = 'Month';

export default Component.extend({
  tagName: 'span',
  campaign: 'below_video_subscribe_button',

  session: injectService(),
  premiumGeo: injectService(),
  tracking: injectService(),

  showPrimeContent: computed.alias('premiumGeo.showPrimeContent'),

  price: computed('channel.product', 'channel.product.isLoaded', 'channel.product.price', function () {
    if (this.get('channel.product') && !this.get('channel.product.isLoaded')) {
      this.get('channel.product').load();
    }
    return this.get('channel.product.price');
  }),

  subscription: computed('channel.isSubscribed.isSubscribed', 'channel.isSubscribed.isLoading', 'channel.id', function() {
    let { isAuthenticated } = this.get('session');
    if (typeof this.get('channel.isSubscribed.isSubscribed') === 'undefined' && isAuthenticated) {
      this.set('channel.isSubscribed', TicketModel.find('user', {channel: this.get('channel.id')}));
      if (!this.get('channel.isSubscribed.isLoaded')) {
        this.get('channel.isSubscribed').load();
      }
    }
    if (this.get('channel.isSubscribed.isLoading')) {
      return undefined;
    }

    return this.get('channel.isSubscribed');
  }),

  // only render for partners (where the channel has a price)
  // and don't render anything until the existing subscription (if any) is loaded
  shouldRender: computed('price', 'subscription', function () {
    return this.get('price') && (!this.get('session.isAuthenticated') || this.get('subscription') !== undefined);
  }),

  // isSubscribed is undefined if loading, true or false if we know
  isSubscribed: computed('subscription.content', function () {
    let sub = this.get('subscription.content');
    return (typeof sub === 'undefined') ? undefined : !!sub.length;
  }),

  // true only if:
  // * user is subbed,
  // * sub is paid for with prime,
  // * sub price is monthly, and
  // * user still has Prime.
  showResub: computed('subscription.content', function() {
    let tickets = this.get('subscription.content');
    if (typeof tickets === 'undefined') {
      return false;
    }

    if (!this.get('session.userData.has_premium')) {
      return false;
    }

    for (let i = 0; i < tickets.length; i++) {
      let ticket = tickets[i];
      let isPrimeSub = ticket.purchase_profile && ticket.purchase_profile.payment_provider === primePaymentProvider;
      let isMonthlyTicket = ticket.product && ticket.product.period === monthlyTicketPeriod;
      if (isPrimeSub && isMonthlyTicket) {
        return true;
      }
    }
    return false;
  }),

  subscribeToText: computed('named', 'channel.displayName', function () {
    let subscribeToTextTemplate = this.get('named') ? i18n('Subscribe to {{channel}}') : i18n('Subscribe');
    return subscribeToTextTemplate.replace('{{channel}}', this.get('channel.displayName'));
  }),

  subscribedToText: computed('named', 'channel.displayName', function () {
    let subscribedToTextTemplate = this.get('named') ? i18n('Subscribed to {{channel}}') : i18n('Subscribed');
    return subscribedToTextTemplate.replace('{{channel}}', this.get('channel.displayName'));
  }),

  actions: {
    toggleHasSubscribedMessage(){
      this.toggleProperty('hasMessage');
    },
    trackSubscribeButtonAction(action, childComponent){
      // childComponent is just passing this from whichever sub childComponent
      // calls the tracing action. It's used to be able to grab whichever extra
      // data that is availible and relevent to the specific action.
      let data = {
        hasPrime: childComponent.get('hasPrime'),
        hasSubCredit: childComponent.get('hasSubCredit'),
        isMenuOpen: childComponent.get('isMenuOpen'),
        canSubscribe: childComponent.get('canSubscribe')
      };

      this.get('tracking').trackEvent({
        event: 'subscribe_button',
        data: {
          action: action,

          browser: navigator.userAgent,
          channel: this.get('channel.id'),
          viewport_height: $(window).height(),
          viewport_width: $(window).width(),

          user_id: this.get('session.userData.id'),
          channel_id: this.get('channel._id'),

          host_channel: this.get('hosterChannel.id'),
          host_channel_id: this.get('hosterChannel._id'),
          vod_id: this.get('vodId'),
          vod_type: this.get('vodType'),

          show_prime_content: this.get('showPrimeContent') || false,
          is_subscribed: this.get('isSubscribed') || false,
          show_resub: this.get('showResub') || false,

          modal: ((this.get('isSubscribed') && this.get('showResub')) ||  (!this.get('isSubscribed')  && this.get('showPrimeContent'))) || false,

          has_prime: data['hasPrime'] || false,
          has_sub_credit: data['hasSubCredit'] || false,
          is_menu_open: data['isMenuOpen'] || false,
          can_subscribe: data['canSubscribe'] || false
        }
      });
    }
  }

});
