import Component from 'ember-component';
import computed from 'ember-computed';
import { assign } from 'ember-platform';
import injectService from 'ember-service/inject';
import $ from 'jquery';
import injectController from 'web-client/utilities/inject-controller';
import SendRouteActionMixin from 'web-client/mixins/send-route-action';

const FOLLOWERS_ONLY_DEFAULT = 30;
const FOLLOWERS_ONLY_DURATIONS = [
  {label: "0 minutes (Any followers)", shorthand: "0 min",  duration: 0},
  {label: "10 minutes (Most used)",    shorthand: "10 min", duration: 10},
  {label: "30 minutes",                shorthand: "30 min", duration: 30},
  {label: "1 hour",                    shorthand: "1 hr",   duration: 60},
  {label: "1 day",                     shorthand: "1 day",  duration: 60 * 24},
  {label: "1 week",                    shorthand: "1 wk",   duration: 60 * 24 * 7},
  {label: "1 month",                   shorthand: "1 mo",   duration: 60 * 24 * 30},
  {label: "3 months",                  shorthand: "3 mo",   duration: 60 * 24 * 30 * 3}
];


// Creates a computed property that acts as an alias, but also tracks changes.
let aliasWithTracking = function(property, settingName) {
    return computed(property, {
      get() {
        return this.get(property);
      },
      set(key, value) {
        let originalValue = this.get(property);
        this.set(property, value);
        let newValue = this.get(property);
        if (originalValue !== newValue) {
          this.trackSettingChange(settingName, newValue);
        }
        return this.get(property);
      }
    });
};

export default Component.extend(SendRouteActionMixin, {
  classNames: ['js-chat-settings-menu', 'chat-settings', 'chat-menu', 'dropmenu'],
  classNameBindings: ['isHidden:hidden'],

  application: injectController(),
  tracking: injectService(),
  session: injectService(),
  settings: injectService('chatSettings'),

  isHidden: false,
  chatUser: null,
  showDisplaySettings: false,

  slowMode: computed.alias('chatUser.slowMode'),

  // We track changes to these settings made through this menu.
  showTimestamps: aliasWithTracking('settings.showTimestamps', 'showTimestamps'),
  darkMode: aliasWithTracking('settings.darkMode', 'darkMode'),
  showModIcons: aliasWithTracking('settings.showModIcons', 'showModIcons'),
  showModerationActions: aliasWithTracking('settings.showModerationActions', 'showModerationActions'),
  showMessageFlags: aliasWithTracking('settings.showMessageFlags', 'showMessageFlags'),

  followerMode: computed.alias('chatUser.followersOnly'),
  followerModeOn: computed.gt('followerMode', -1),
  followerModeDurations: FOLLOWERS_ONLY_DURATIONS,
  followerModeSelection: computed('settings.lastUsedFollowerDurations', 'followerMode', function() {
    // Selection priority:
    // 1) If followers mode is on, the active mode
    // 2) If a saved "last used" duration is present, use that
    // 3) The default value
    let actualMode = this.get('followerMode');
    let selection = actualMode;
    let channelName = this.get('chatUser.roomProperties.id');
    if (actualMode === undefined || actualMode === -1) {
      let lastUsed = this.get('settings').getFollowerSelection(channelName);
      if (lastUsed !== undefined) {
        selection = lastUsed;
      } else {
        selection = FOLLOWERS_ONLY_DEFAULT;
      }
    }
    return selection;
  }),
  followerModeSelectionShorthand: computed('followerModeSelection', function() {
    let selectedMode = this.get('followerModeSelection');
    let durations = this.get('followerModeDurations');
    let out = "custom";
    durations.forEach(function(duration) {
      if (duration.duration === selectedMode) {
        out = duration.shorthand;
      }
    });

    return out;
  }),

  isLoggedIn: computed.readOnly('session.isAuthenticated'),

  didInsertElement() {
    this._super(...arguments);

    if (!this.get('isLoggedIn')) {
      this.addEventListener('.js-chat-colors .chat-colors-swatch', 'click', () => {
        this.sendRouteAction('handleNotLoggedIn', { mpSourceAction: 'chat' });
      });
    }

    // the checkbox view does not seem to have an action configuration
    this.addEventListener(this.element, 'click', (event) => {
      let slowModeCheckbox = this.$('.js-slow-mode-checkbox');
      if (slowModeCheckbox.length && (event.target === slowModeCheckbox[0] || $.contains(slowModeCheckbox[0], event.target))) {
        if (this.get('chatUser.slowMode')) {
          this.get('chatUser.tmiRoom').stopSlowMode();
        } else {
          this.get('chatUser.tmiRoom').startSlowMode();
        }

        this.trackSettingChange('slowMode', this.get('chatUser.slowMode'));
      }

      let followerModeCheckbox = this.$('.js-followers-mode-checkbox');
      if (followerModeCheckbox.length && (event.target === followerModeCheckbox[0] || $.contains(followerModeCheckbox[0], event.target))) {
        if (this.get('followerModeOn')) {
          this.get('chatUser.tmiRoom').stopFollowersMode();
        } else {
          let value = this.get('followerModeSelection');
          this.get('chatUser.tmiRoom').setFollowersMode(value);
        }

        this.trackSettingChange('followerMode', this.get('followerModeOn'));
      }
    });
  },

  // Tracks changes to settings the user makes through this menu.
  trackSettingChange(settingName, settingValue, otherData) {
    let room = this.get('chatUser');
    if (room) {
      this.get('tracking').trackEvent({
        event: 'chat_client_setting_changed',
        data: assign({
          setting_name: settingName,
          new_value: settingValue.toString()
        }, otherData, room.getTrackingData())
      });
    }
  },

  actions: {
    clearChat() {
      this.get('chatUser.tmiRoom').clearChat();
    },

    hideChat() {
      this.set('isHidden', true);
      this.get('hideChat')();

      this.trackSettingChange('hideChat', true);
    },

    popoutChat() {
      this.set('isHidden', true);
      this.get('popoutChat')();
    },

    toggleDisplaySettings() {
      this.toggleProperty('showDisplaySettings');
    },

    setFollowersDuration(duration) {
      if (this.get('followerModeOn')) {
        this.get('chatUser.tmiRoom').setFollowersMode(duration);
      }
      let channelName = this.get('chatUser.roomProperties.id');
      this.get('settings').setFollowerSelection(channelName, duration);

      // Track when the user changes the follower duration through this menu,
      // and whether follower mode is on or off.
      this.trackSettingChange('followerDuration', duration, {
        follower_mode_on: this.get('followerModeOn')
      });
    }
  }
});
