import Mixin from 'ember-metal/mixin';
import injectService from 'ember-service/inject';
import computed from 'ember-computed';
import { assign } from 'ember-platform';
import getOwner from 'ember-owner/get';

const FOLLOWED_VIDEO_CLICK_EVENT = 'follow_directory_click';

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

  sendTracking(object, position, section, properties={}) {
    // Position is checked here as sidebar clicks will trigger the action handlers.
    if (position === undefined) { return; }

    let data = assign({}, this.trackingData());
    data = assign(data, properties);
    data = assign(data, {section, position});

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

  applicationRoute: computed(function() {
    return getOwner(this).lookup('route:application');
  }),

  _bubbleAction(actionName, thing){
    let applicationRoute = this.get('applicationRoute');
    let actionHandler = applicationRoute.actions[actionName];
    // Call this action specifically because the route-action helper does not support bubbling
    actionHandler.call(applicationRoute, thing);
  },

  actions: {
    /**
     TODO: this did not take into account the use case where clicking on one's own channel
     page in the left navbar does not pass a channel object into this action.
     the action handler at the root level assumes channel is an optional parameter,
     but this particular handler was making it mandatory.
     */
    handleStreamClick(channel, position) {
      if (channel) {
        this.sendTracking(channel, position, 'channels', {'channel': channel.id});
      }
      this._bubbleAction('handleStreamClick', channel);
    },

    handleGameClick(game, position) {
      this.sendTracking(game, position, 'games');
      this._bubbleAction('handleGameClick', game);
    },

    handleVideoClick(video, position, total) {
      this.sendTracking(video, position, 'videos');
      let applicationRoute = this.get('applicationRoute');
      let actionHandler = applicationRoute.actions['handleVideoClick'];
      // Call this action specifically because the route-action helper does not support bubbling
      actionHandler.call(applicationRoute, video, position, total);
    },

    handleHostClick(host, position) {
      this.sendTracking(host, position, 'hosts', { 'channel': host.target.id, 'host_channel': host.id });
      this._bubbleAction('handleHostClick', host);
    }
  }
});
