import Component from 'ember-component';
import computed from 'ember-computed';
import Ember from 'ember';
import injectService from 'ember-service/inject';
import { DEFAULT_BANNER } from 'web-client/utilities/urls/communities';
import { storageFor } from 'ember-local-storage';
import $ from 'jquery';
import run from 'ember-runloop';
import { htmlSafe } from 'ember-string';

const BANNER_SCROLL_EVENT = 'scroll.tag-banner';
const { Handlebars } = Ember;
const { escapeExpression } = Handlebars.Utils;

export default Component.extend({
  pubsub: injectService(),
  tracking: injectService(),

  classNames: ['ct-banner-container'],
  classNameBindings: ['hideBanner:ct-banner-container--off', 'isDefault:ct-banner-container--img-none'],
  currentTag: null,
  game: null,
  channel: null,
  channels: null,
  settings: storageFor('creative-settings'),

  hideBanner: computed('currentTag.id', function () {
    return this.get('currentTag') !== null && !this.get('currentTag.isCommunity');
  }),

  banner: computed('currentTag.banner', function () {
    return this.get('currentTag.banner') || DEFAULT_BANNER;
  }),

  bannerBackgroundImageStyle: computed('banner', function () {
    return htmlSafe(`background-image: url(${ escapeExpression(this.get('banner')) });`);
  }),

  isDefault: computed('currentTag.banner', 'hideBanner', function () {
    return (!this.get('currentTag.banner') || this.get('hideBanner'));
  }),

  parallaxReady: false,
  $page: null,
  $pageContent: null,

  didInsertElement() {
    this._super(...arguments);
    run.scheduleOnce('afterRender', this, () => {
      this.set('parallaxReady', true);
      this.attachParallax();
    });
  },

  didReceiveAttrs() {
    this._super(...arguments);
    let currentChannelSub = this.get('currentChannelSub');
    if (currentChannelSub) {
      this.unsubscribeChannelEvents(currentChannelSub);
    }
    let channel = this.get('channel');
    if (channel) {
      this.subscribeChannelEvents(channel);
      this.set('currentChannelSub', channel);
    }
  },

  didRender() {
    if (this.get('parallaxReady')) {
      this.attachParallax();
    }
  },

  attachParallax() {
    let $page = $('#main_col .tse-scroll-content');
    let $pageContent = $('#main_col #directory-list');
    let $banner = this.$('.ct-banner__img');
    let $topbar = this.$('.ct-banner__topbar');
    let $downbar = this.$('.ct-bar');
    if (!this.get('currentTag.banner') || this.get('hideBanner')) {
      $page.off('scroll.tag-banner');
      $page.scrollTop(0);
    }
    else {
      $pageContent.css('min-height', $page.height() + $banner.height());
      $page.scrollTop($(window).height() * 0.70);
    }
    $page.off(BANNER_SCROLL_EVENT).on(BANNER_SCROLL_EVENT, () => {
      $downbar.toggleClass('ct-bar--active', $page.scrollTop() > ($banner.height() + $downbar.height()));
      if (this.get('currentTag.banner') && !this.get('hideBanner')) {
        $banner.css('-webkit-transform', `translateY(${Math.floor($page.scrollTop()/2)}px)`);
        let showTopbar = $page.scrollTop() < 5;
        $topbar.toggleClass('ct-banner__topbar--active', showTopbar);
        if (showTopbar) {
          let community = this.get('currentTag.id');
          this.get('tracking').trackEventOnce({
            event: 'community_topbar_show',
            namespace: `community_topbar_show-${community}`,
            data: { community }
          });
        }
      }
    });
  },

  willDestroyElement() {
    this._super(...arguments);
    let channel = this.get('channel');
    if (channel) {
      this.unsubscribeChannelEvents(channel);
    }
  },

  pubsubTopic(channel) {
    return channel ? `channel.${channel.get('name')}` : null;
  },

  subscribeChannelEvents(channel) {
    this.get('pubsub').on(this.pubsubTopic(channel), this, this.handlePubsub);
  },

  unsubscribeChannelEvents(channel) {
    this.get('pubsub').off(this.pubsubTopic(channel), this, this.handlePubsub);
  },

  handlePubsub(payload) {
    switch(payload.type) {
      case 'status':
        this.controller.set('channel.status', payload.status);
        break;
    }
  }
});
