import computed from 'ember-computed';
import Component from 'ember-component';
import observer from 'ember-metal/observer';
import injectService from 'ember-service/inject';

export default Component.extend({
  classNames: ['notification-controls', 'cn-notification-controls'],

  isVisible: computed.bool('follow.isFollowing'),
  isMenuOpen: false,

  hosterChannelId: '',

  store: injectService(),
  tracking: injectService(),
  // NOTICE: The login service is deprecated, plesase use the session service.
  // See app/services/SESSION.md for more details.
  login: injectService(),
  isLoggedIn: computed.readOnly('login.isLoggedIn'),

  channelNotificationsEnabled: computed.reads('follow.notifications'),

  follow: computed('channel.id', 'isLoggedIn', function () {
    let channel = this.get('channel.id');
    let isLoggedIn = this.get('isLoggedIn');

    if (!channel || !isLoggedIn) {
      return null;
    }

    let store = this.get('store');
    return store.findRecord('follow', channel);
  }),

  isFollowInitialized: null,

  openMenuIfFollowed: observer('follow.isFollowing', function () {
    if (this.get('follow.isFollowing') === undefined) {
      return;
    }
    if (!this.get('isFollowInitialized')) {
      // This gets called once when you first load the page and initialize the
      // button. In that situation, we shouldn't open the menu.
      this.set('isFollowInitialized', true);

    } else if (this.get('follow.isFollowing')) {
      // This line of code executes when the "follow" button is clicked to automatically show notification controls.
      // We wrap it in runTask because the ClickOutsideMixin executes the "click outside" callback (which hides the menu) before this runs.
      // We want this to run after that, so push it to the end of the event loop.
      this.runTask(() => {
        this.set('isMenuOpen', true);
      }, 0);
    }
  }),

  currentUser: computed('isLoggedIn', 'login.userData.login', function () {
    if (!this.get('isLoggedIn')) {
      return;
    }
    let id = this.get('login.userData.login');
    return this.get('store').findRecord('user', id);
  }),

  globalEmailEnabled: computed.alias('currentUser.notifications.email'),
  pushEnabled: computed.alias('currentUser.notifications.push'),
  globalNotificationsEnabled: computed.or('pushEnabled', 'globalEmailEnabled'),
  enableNotificationToggle: computed.and('channelNotificationsEnabled', 'globalNotificationsEnabled'),

  didInsertElement() {
    // check the flag right away to force a fetch for the currentUser if needed.
    // That way the UI will be accurate when the user opens the menu.
    this.get('globalNotificationsEnabled');
  },

  _hideMenu: observer('canShowMenu', function() {
    if (!this.get('canShowMenu')) {
      this.set('isMenuOpen', false);
    }
  }),

  actions: {
    toggleMenu() {
      this.toggleProperty('isMenuOpen');
    },

    notificationToggle() {
      if (!this.get('globalNotificationsEnabled')) {
        this.get('tracking').trackEvent({
          event: 'notification_disabled_click',
          data: {
            notification: this.get('channelNotificationsEnabled')
          }
        });
        return;
      }

      let channelNotificationsEnabled = this.toggleProperty('channelNotificationsEnabled');
      let follow = this.get('follow');
      follow.set('notifications', channelNotificationsEnabled);
      follow.get('content').save();

      let data = {
        platform: 'web',
        src: this.get('name'),
        channel: this.get('channel.id'),
        game: this.get('channel.game'),
        notifications: channelNotificationsEnabled
      };

      if (this.get('name') === 'host_mode') {
        data.host_channel = this.get('hosterChannelId');
      }

      this.sendAction('track', 'notification_change', this.get('channel'), data);
    }
  }
});
