/* globals Twitch */

import Ember from 'ember';
import Component from 'ember-component';
import computed from 'ember-computed';
import injectService from 'ember-service/inject';
import ClickOutsideMixin from 'web-client/mixins/click-outside';

const { getOwner } = Ember;

// TODO(mikeche): Move all presence-related code in repo to constants.
const VISIBILITY_SHARE_SETTINGS_FULL = 'full';
const VISIBILITY_EVENT = 'share_mode_change';
const VISIBILITY_EVENT_MODE_ONLINE = 'online';
const VISIBILITY_EVENT_MODE_INVISIBLE = 'invisible';

export default Component.extend(ClickOutsideMixin, {
  tagName: 'div',
  classNames: ['top-nav__drawer-anchor', 'flex'],

  conversations: injectService('twitch-conversations/conversations'),
  navigation: injectService(),
  presence: injectService('twitch-presence/presence'),
  session: injectService(),
  tracking: injectService(),

  // Properties for drawer links.
  userChannelUrl: computed(function () {
    return Twitch.uri.channel(this.get('session.userData.login'));
  }),

  managerUrl: computed(function () {
    let channelURL = Twitch.uri.channel(this.get('session.userData.login'));
    return `${channelURL}/manager/past_broadcasts`;
  }),

  dashboardsUrl: computed(function () {
    let channelURL = Twitch.uri.channel(this.get('session.userData.login'));
    return `${ channelURL }/dashboard`;
  }),

  init() {
    this._super(...arguments);
    this.router = getOwner(this).lookup('router:main');
    this.router.on('willTransition', this, 'closeDrawer');
  },

  willDestroy() {
    this.router.off('willTransition', this, 'closeDrawer');
    this._super(...arguments);
  },

  closeDrawer() {
    this.set('navigation.isDrawerOpen', false);
  },

  clickedOutside() {
    this.closeDrawer();
  },

  actions: {
    toggleDrawer() {
      this.get('navigation').toggleProperty('isDrawerOpen');
    },

    // TODO(mikeche): Right now this is duplicated from twitch-presence/selector.
    // We should refactor to shared logic.
    setVisibility(visibility) {
      if (this.get('presence.settings.share') !== visibility) {
        this.get('tracking').trackEvent({
          event: VISIBILITY_EVENT,
          data: {
            login: Twitch.user.login(),
            share_mode: visibility === VISIBILITY_SHARE_SETTINGS_FULL ? VISIBILITY_EVENT_MODE_ONLINE : VISIBILITY_EVENT_MODE_INVISIBLE
          }
        });
      }
      this.get('presence').setVisibility(visibility);
    },

    toggleDoNotDisturb(){
      this.get('conversations').toggleDND();
    }
  }
});
