/* globals Twitch */
import Component from 'ember-component';
import computed from 'ember-computed';
import injectService from 'ember-service/inject';
import $ from 'jquery';

export default Component.extend({
  experiments: injectService(),
  recsHoldout: injectService('recs-holdout'),
  similarChannels: injectService(),
  storage: injectService(),
  conversations: injectService('twitch-conversations/conversations'),
  globals: injectService(),
  layout: injectService(),
  session: injectService(),
  tracking: injectService(),
  navigation: injectService(),
  browse: injectService(),

  isBrowseExperimentEnabled: computed.readOnly('browse.isBrowseExperimentEnabled'),

  isRecommendedChannelsEnabled: computed('experiments', function () {
    let experiments = this.get('experiments');
    if (experiments) {
      experiments.getExperimentValue('RECOMMENDED_CHANNELS').then((value) => {
        if (this.isDestroyed) { return; }
        this.set('isRecommendedChannelsEnabled', value === 'yes');
      });
    }
    return false;
  }),

  isCreativeLinkEnabled: computed('experiments', function () {
    let experiments = this.get('experiments');
    if (experiments) {
      experiments.getExperimentValue('CREATIVE_SIDEBAR_NAVIGATION').then((value) => {
        if (this.isDestroyed) { return; }
        this.set('isCreativeLinkEnabled', value === 'yes');
      });
    }
    return false;
  }),

  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`;
  }),

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

    this._initBottomMenu();
    this._initExtraMenuDropDown();
    this._initFooterMoreToggle();
    this._initSmallNavFlyouts();
    this._initScrollBar();
  },

  didRender() {
    this._initTooltips();
  },

  willDestroyElement() {
    $('body').teardownOverlay();

    if (this.$('#left_col .scroll').data('plugin_TrackpadScrollEmulator')) {
      $('#left_col .scroll').TrackpadScrollEmulator('destroy');
    }

    /* _initNav */
    let element = this.$('.loggedin');
    element.off(`mouseenter.${this.elementId}`);
    element.off(`mouseleave.${this.elementId}`);

    /* _initFooterMoreToggle */
    $('#footer .show-more-toggle').off(`click.${this.elementId}`);

    /* _initExtraMenuDropDown */
    $('.left-col-dropdown').off(`click.${this.elementId}`);

    /* _initSmallNavFlyouts */
    $('#small_search a').off(`click.${this.elementId}`);

    this._tipsySelector.teardownTipsy();
    this._super(...arguments);
  },

  _initBottomMenu() {
    let element = this.$('.loggedin');
    element.on(`mouseenter.${this.elementId}`, () => {
      let h = $('#user_display_name').outerHeight() + $('#account_actions').outerHeight();
      this.$().stop().animate({height: h}, 250, 'swing', false);
    });
    element.on(`mouseleave.${this.elementId}`, () => {
      let h = $('#user_display_name').outerHeight();
      $(this).stop().animate({height: h}, 250, 'swing', false);
    });
  },

  _initTooltips() {
    this._tipsySelector = $('#js-warp a, #small_search button, #small_more button').tipsy({ gravity: 'w' });
  },

  _initScrollBar() {
    $('#left_col .scroll').TrackpadScrollEmulator({
      wrapContent: false,
      scrollbarHideStrategy: 'rightAndBottom'
    });
  },

  _initSmallNavFlyouts() {
    $('#small_search a').on(`click.${this.elementId}`, () => {
      $('.st-autocomplete-sidebar').empty();
      $('#sidebar_query').val('');
    })
    .flyout('small_search', {
      anchor: 'mid',
      trigger: 'autocomplete-small',
      focusOnLoad: '.search_input'
    });

    $('#small_more button').flyout('small_more', {'anchor': 'mid'});
    $('#small_account a').flyout('small_account', {
      anchor: 'bot',
      data: {
        user: this.get('login.userData.login')
      }
    });
  },

  _initExtraMenuDropDown() {
    if ($('.extra-menu li').hasClass('selected')) {
      let extraMenuHeight = $('.nav_section .extra-menu')[0].scrollHeight;
      $('.nav_section .extra-menu').css({height: extraMenuHeight});
      $('.left-col-dropdown').removeClass('collapsed');
    }

    $('.left-col-dropdown').on(`click.${this.elementId}`, function () {
      if ($(this).hasClass('collapsed')) {
        // get height of hidden menu
        let extraMenuHeight = $('.nav_section .extra-menu')[0].scrollHeight;
        $('.nav_section .extra-menu').animate({height: extraMenuHeight}, 80);
        $(this).removeClass('collapsed');
      } else {
        $('.nav_section .extra-menu').animate({height: 0}, 80);
        $(this).addClass('collapsed');
      }
    });
  },

  // clean this code up if it's decided to go on prod!
  _initFooterMoreToggle() {
    $('#footer .show-more-toggle').on(`click.${this.elementId}`, function () {
      if ($(this).hasClass('more')) {
        // show hidden menus
        $('.extra-footer-link').show();
        $(this).removeClass('more');
      } else {
        $('.extra-footer-link').hide();
        $(this).addClass('more');
      }
    });
  },

  actions: {
    onClick(user) {
      let login = user.get('login');
      this.get('conversations').startConversationForUsername(login).then((conversation) => {
        this.get('tracking').trackEvent({
          event: 'chat_convo_create',
          data: {
            conversation_id: conversation.get('thread.id'),
            login: this.get('session.userData.login'),
            target_login: login,
            source: 'friends'
          }
        });
      });
    },

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