/* globals Twitch */

import computed from 'ember-computed';
import Component from 'ember-component';
import injectService from 'ember-service/inject';
import { BITS_URL } from 'web-client/utilities/urls/static-cdn';
import { htmlSafe } from 'ember-string';
import times from 'web-client/utilities/times';

const CHAT_IMAGE_URL = `${BITS_URL}/light/static/1/chat.png`;
const READ_MORE_LINK_LOCATION = 'http://link.twitch.tv/jfiyp';
const YOUR_DASHBOARD_LINK_LOCATION = 'http://link.twitch.tv/fgtgb';

/*
  Broadcaster upsell that shows up when a broadcaster in an eligible country,
  but that has not enabled bits, loads their own channel.

  Has some rudimentary pagination.
*/

export default Component.extend({
  classNames: ['js-bits-broadcaster-notification'],

  bitsRoom: injectService(),
  bitsStrings: injectService(),
  tracking: injectService(),
  session: injectService(),

  pageIndex: 0,

  userId: computed.readOnly('session.userData.id'),
  userName: computed.readOnly('session.userData.login'),

  channelId: computed.readOnly('bitsRoom.channelId'),
  channelName: computed.readOnly('bitsRoom.channelName'),

  chatImageUrl: CHAT_IMAGE_URL,

  init() {
    this._flowStepsSeen = {};
    this._pageCount = 2;
    this._super(...arguments);
    this._trackFlow('flow_start');
  },

  readMoreLink: computed('bitsStrings.isLoaded', function () {
    if (!this.get('bitsStrings.isLoaded')) {
      return '';
    }

    let bitsStringsSvc = this.get('bitsStrings');

    return htmlSafe(`<a href="${READ_MORE_LINK_LOCATION}" class="bits-card__link" target="_blank">${bitsStringsSvc.getString('eligible_for_bits_blog_link')}</a>`);
  }),

  yourDashboardLink: computed('bitsStrings.isLoaded', function () {
    if (!this.get('bitsStrings.isLoaded')) {
      return '';
    }

    let bitsStringsSvc = this.get('bitsStrings');

    return htmlSafe(`<a href="${YOUR_DASHBOARD_LINK_LOCATION}" class="bits-card__link" target="_blank">${bitsStringsSvc.getString('eligible_for_bits_dashboard_link')}</a>`);
  }),

  pageDots: computed('pageIndex', function () {
    let dots = [];

    times(this._pageCount, (index) => {
      dots.push({
        pageNum: index,
        isSelected: index === this.get('pageIndex')
      });
    });

    return dots;
  }),

  actions: {
    nextPage() {
      let newPageIndex = this.incrementProperty('pageIndex');
      this._trackElementAction(`next_${newPageIndex}`);
      this._trackFlowStep(newPageIndex);
    },
    completePromo() {
      this.get('bitsRoom').completeRecipientCanEnableFTUE();
      this._trackElementAction('get_started');
      this._trackFlow('flow_complete_get_started');
    },
    goToPage(num) {
      let originalPageIndex = this.get('pageIndex');
      this.set('pageIndex', num);

      this._trackElementAction(`dot_${++num}`);
      if (originalPageIndex < 1) {
        this._trackFlowStep(++originalPageIndex);
      }
    },

    close() {
      this.get('bitsRoom').dismissRecipientCanEnableFTUE();
      this._trackElementAction('close');
      this._trackFlow('flow_complete_close');
    }
  },

  _trackElementAction(element, actionType) {
    let eventData = {
        client_time: new Date().getTime(),
        device_id: Twitch.idsForMixpanel.getOrCreateUniqueId(),
        login: this.get('userName'),
        login_id: this.get('userId'),
        channel: this.get('channelName'),
        channel_id: this.get('channelId'),
        element: element,
        action_type: actionType || 'click'
    };

    this.get('tracking').trackEvent({
      event: 'bits_partner_onboarding_elements',
      data: eventData
    });
  },

  _trackFlow(step) {
    let eventData = {
        client_time: new Date().getTime(),
        device_id: Twitch.idsForMixpanel.getOrCreateUniqueId(),
        login: this.get('userName'),
        login_id: this.get('userId'),
        channel: this.get('channelName'),
        channel_id: this.get('channelId'),
        step: step
    };

    this.get('tracking').trackEvent({
      event: 'bits_partner_onboarding_flow',
      data: eventData
    });
  },

  _trackFlowStep(newPageIndex) {
    let flowStepCompleted = `flow_step_${newPageIndex}`;

    if (!this._flowStepsSeen.hasOwnProperty(flowStepCompleted)) {
      this._flowStepsSeen[flowStepCompleted] = '';
      this._trackFlow(flowStepCompleted);
    }
  }
});
