/* globals Twitch */

import Route from 'ember-route';
import injectService from 'ember-service/inject';

export default Route.extend({
  // NOTICE: The login service is deprecated, plesase use the session service.
  // See app/services/SESSION.md for more details.
  login: injectService(),
  feeds: injectService(),
  globals: injectService(),
  tracking: injectService(),

  renderTemplate(controller, model) {
    this.render('channel/post', {
      outlet: 'modal',
      into: 'application',
      model: model
    });
  },

  model(params) {
    let feedsService = this.get('feeds');
    let user = this.modelFor('user');

    this.set('postId', params.post_id);
    return feedsService.getPost(params.post_id, user.id).then((model) => {
      return model;
    }, (response) => {
      this.set('postErrorResponse', response);
      return null;
    });
  },

  setupController() {
    this._super(...arguments);
    this.controllerFor('channel').set('pauseHostMode', true);
  },

  resetController(controller, isExiting) {
    if (isExiting) {
      this.controllerFor('channel').set('pauseHostMode', false);
    }
  },

  afterModel(model) {
    let channel = this.modelFor('channel');
    let user = this.get('login.userData');
    let postId = model ? model.id : this.get('postId');
    let deleted = false;
    let userOptedOut = false;

    if (!model) {
      let errorResponse = this.get('postErrorResponse');
      let responseStatus = JSON.parse(errorResponse.responseText);

      if (responseStatus.status === 404) {
        deleted = true;
      } else {
        userOptedOut = true;
      }
    }

    this.get('tracking').trackEvent({
      event: 'feed_update_directview',
      data: {
        status_update_id: postId,
        device_id: Twitch.idsForMixpanel.getOrCreateUniqueId(),
        login: user ? user.login : '',
        channel: channel.get('id'),
        status_update_url: this.get('router.url'),
        deleted,
        user_opted_out: userOptedOut
      }
    });
    this._super(...arguments);
  },

  _closeModal() {
    let channel = this.modelFor('channel');
    this.transitionTo('channel.index', channel);
  },

  actions: {
    deletePost(post) {
      return this.get('feeds').deleteMessage(post).then(() => {
        this._closeModal();
      });
    },

    closeModal() {
      this._closeModal();
    }
  }
});
