/* globals Twitch */
import Mixin from 'ember-metal/mixin';
import Video from 'web-client/models/video';
import injectService from 'ember-service/inject';
import { assign } from 'ember-platform';

export default Mixin.create({
  tracking: injectService(),

  _buildCommonProperties() {
    let pageviewProperties = Twitch.tracking.funnel.pageviewProperties || {};
    return {
      location: pageviewProperties.location,
      medium: pageviewProperties.medium,
      content: pageviewProperties.content,
      page_session_id: pageviewProperties.page_session_id,
      tab_session_id: pageviewProperties.tab_session_id
    };
  },

  _buildItemSectionLoadObject(items, index) {
    let props = this._buildCommonProperties();
    let itemProps = {
      carousel_content: this.get('trackingContent'),
      section_index: index,
      rendered_item_list: items.join(','),
      rendered_item_count: items.length,
      num_recs_visible: this.get('numRecsViewable'),
      source_game: this.get('sourceContent.game'),
      source_vod_id: this.get('sourceContentVodId'),
      source_channel: this.get('sourceContent.name'),
      source_item_type: this.get('sourceContentBroadcastType')
    };
    return assign(props, itemProps);
  },

  _buildItemClickObject(item, index) {
    let props = this._buildCommonProperties();
    let itemProps = {
      item_id: item.id,
      section_index: item._carouselSectionIndex,
      item_index: index,
      channel: item.channel.name,
      game: item.game,
      // this is handled in a route action, so we have to look at the passed in props to the item
      carousel_content: item._carouselContent,
      source_game: item._sourceGame,
      source_vod_id: item._sourceVodId,
      source_channel: item._sourceChannel,
      source_item_type: item._sourceItemType
    };
    return assign(props, itemProps);
  },

  _enrichContentObject(content) {
    content.game = content.get('game');
    content.channel.name = content.get('channel.name');
    return content;
  },

  _trackCarouselItemClick(item, index) {
    let properties = this._buildItemClickObject(item, index);
    this.get('tracking').trackEvent({
      event: 'item_section_click',
      data: properties
    });
  },

  trackItemSectionLoad(items, index) {
    let properties = this._buildItemSectionLoadObject(items, index);
    this.get('tracking').trackEvent({
      event: 'item_section_load',
      data: properties
    });
  },

  trackCarouselVideoItemClick(video, index) {
    if (video instanceof Video) {
      video = this._enrichContentObject(video);
    }
    this._trackCarouselItemClick(video, index);
  },

  trackCarouselStreamItemClick(stream, index) {
    let enrichedStream = this._enrichContentObject(stream);
    this._trackCarouselItemClick(enrichedStream, index);
  }
});
