/* 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';

const COMPLETE_PROMO_ACTION = 'completePromo';
const COMPLETE_EVO_PROMO_ACTION = 'learnMoreEvo';
const NEXT_PAGE_ACTION = 'nextPage';

/*
  Tutorial/Promotional upsell that shows up on first load.
    * exitPromo - action called when the close button is clicked

  Has some rudimentary pagination.
*/

export default Component.extend({
  classNames: ['js-bits-intro-promo'],
  bitsRoom: injectService(),
  bitsStrings: injectService(),
  tracking: injectService(),
  session: injectService(),

  /* Defaults */
  pageIndex: 0,

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

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

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

  /* Attributes */
  isLoaded: computed('bitsStrings.isLoaded', 'type', function () {
    let bitsStringsSvc = this.get('bitsStrings');
    let type = this.get('type');

    if (!this.get('bitsStrings.isLoaded')) {
      return false;
    }

    if (type === 'default') {
      let showSupportLink = `<a href="http://link.twitch.tv/ddzbn" class="bits-card__link" target="_blank">${bitsStringsSvc.getString('promo_card_link_support')}</a>`;
      let earnLink = `<a href="http://link.twitch.tv/qsbgq" class="bits-card__link" target="_blank">${bitsStringsSvc.getString('promo_card_link_earn')}</a>`;

      this.set('pages', [
        {
          imageName: '',
          showBitsEmotes: true,
          title: bitsStringsSvc.getString('promo_card_one_title'),
          body: bitsStringsSvc.getString('promo_card_one_body'),
          buttonText: bitsStringsSvc.getString('promo_card_btn_next'),
          buttonAction: NEXT_PAGE_ACTION
        },
        {
          imageName: 'chat',
          showBitsEmotes: false,
          title: bitsStringsSvc.getString('promo_card_two_title'),
          body: bitsStringsSvc.getString('promo_card_two_body').replace('%{showSupportLink}', showSupportLink),
          buttonText: bitsStringsSvc.getString('promo_card_btn_next'),
          buttonAction: NEXT_PAGE_ACTION
        },
        {
          imageName: 'badges',
          showBitsEmotes: false,
          title: bitsStringsSvc.getString('promo_card_three_title'),
          body: bitsStringsSvc.getString('promo_card_three_body').replace('%{earnLink}', earnLink),
          buttonText: bitsStringsSvc.getString('promo_card_btn_complete'),
          buttonAction: COMPLETE_PROMO_ACTION
        }
      ]);
    } else if (type === 'evo') {
      this.set('pages', [
        {
          imageName: '',
          showBitsEmotes: false,
          title: "Cheer for Players at Capcom Cup!",
          body: "You can now Cheer with Bits for your favorite players during Capcom Cup! Cheering shows support for the players and hype for Capcom Cup. Buy some Bits to get started, or <a href='http://capcomprotour.com/twitch-cheering-capcom-cup/' target='_blank'/>click here for more on how it works.</a>",
          buttonText: bitsStringsSvc.getString('promo_card_btn_next'),
          buttonAction: NEXT_PAGE_ACTION
        },
        {
          imageName: '',
          showBitsEmotes: false,
          title: bitsStringsSvc.getString('promo_evo_title_2'),
          body: "To show your support for a specific player, buy Bits and Cheer for them by sending a chat message with cheer and a number, and their hashtag. For example,<span style='display:block'><b>cheer100 #daigo</b></span>",
          buttonText: 'Learn More',
          buttonAction: COMPLETE_EVO_PROMO_ACTION
        }
      ]);
    }

    return true;
  }),

  pageDots: computed('pages', 'pageIndex', function () {
    let pages = this.get('pages');

    return pages.map((pg, index) => {
      return {
        pageNum: index,
        isSelected: index === this.get('pageIndex')
      };
    });
  }),

  title: computed('pageIndex', 'pages', function () {
    let pageIndex = this.get('pageIndex');
    let pages = this.get('pages');

    return pages[pageIndex].title;
  }),

  body: computed('pageIndex', 'pages', function () {
    let pageIndex = this.get('pageIndex');
    let pages = this.get('pages');

    return pages[pageIndex].body;
  }),

  buttonText: computed('pageIndex', 'pages', function () {
    let pageIndex = this.get('pageIndex');
    let pages = this.get('pages');

    return pages[pageIndex].buttonText;
  }),

  buttonAction: computed('pageIndex', 'pages', function () {
    let pageIndex = this.get('pageIndex');
    let pages = this.get('pages');

    return pages[pageIndex].buttonAction;
  }),

  showBitsEmotes: computed('pageIndex', 'pages', function () {
    let pageIndex = this.get('pageIndex');
    let pages = this.get('pages');

    return pages[pageIndex].showBitsEmotes;
  }),

  imageUrl: computed('pageIndex', 'pages', function () {
    let pageIndex = this.get('pageIndex');
    let pages = this.get('pages');

    if (pages[pageIndex].imageName !== '') {
      return `${BITS_URL}/light/static/1/${pages[pageIndex].imageName}.png`;
    }
    return '';
  }),

  actions: {
    buttonPressed() {
      let buttonAction = this.get('buttonAction');

      switch (buttonAction) {
        case NEXT_PAGE_ACTION: {
          let newPageIndex = this.incrementProperty('pageIndex');
          this._trackElementAction(`next_${newPageIndex}`);
          this._trackFlowStep(newPageIndex);
          break;
        }
        case COMPLETE_PROMO_ACTION:
          this.get('bitsRoom').completeFTUE();
          this._trackElementAction('get_started');
          this._trackFlow('flow_complete_get_started');
          break;
        case COMPLETE_EVO_PROMO_ACTION:
          window.open('http://capcomprotour.com/twitch-cheering-capcom-cup/');
          break;
      }
    },

    goToPage(num) {
      let originalPageIndex = this.get('pageIndex');
      this.set('pageIndex', num);

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

    close() {
      this.get('bitsRoom').dismissFTUE();
      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_user_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_user_onboarding_flow',
      data: eventData
    });
  },

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

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