/* globals i18n, Twitch, _, ZeroClipboard, location */

import Component from 'ember-component';
import computed from 'ember-computed';
import $ from 'jquery';
import { htmlSafe } from 'ember-string';

import { JTV_USER_PICTURES_404_USER_150X150_URL } from 'web-client/utilities/urls/static-cdn';

export default Component.extend({
  openedBalloon: '',
  product: computed.alias('ticket.product'),

  productNameLabel: computed('product.ticket_type', 'product.partner.display_name', 'product.name', function () {
    let product = this.get('product');
    if (product.ticket_type === 'chansub') {
      return `${product.partner.display_name} - ${product.name}`;
    }
    return product.name;
  }),

  productOwnerTypeLabel: computed('product.ticket_type', function () {
    let product = this.get('product');
    if (product.ticket_type === 'chansub') {
      return 'Go to Channel';
    } else if (product.ticket_type === 'teamsub') {
      return 'Go to Team page';
    } else if (product.ticket_type === 'turbo') {
      return 'Turbo settings';
    }
    return null;
  }),

  // productOwnerLink should be generated behind the api
  productOwnerLink: computed('product.owner_name', function () {
    let product = this.get('product');
    if (product.ticket_type === 'chansub') {
      return Twitch.uri.channel(product.owner_name);
    } else if (product.ticket_type === 'teamsub') {
      return Twitch.uri.team(product.owner_name);
    } else if (product.ticket_type === 'turbo') {
      return '/settings/turbo';
    }
    return null;
  }),

  isTurbo: computed.equal('product.ticket_type', 'turbo'),

  logo: computed('product.partner.logo', 'isTurbo', function () {
    if (this.get('isTurbo')) {
      return '/images/xarth/turbo_profile_logo.png';
    }

    return this.get('product.partner.logo') || JTV_USER_PICTURES_404_USER_150X150_URL;
  }),

  profileBannerBackgroundColorStyle: computed('product.partner.profile_banner_background_color', function () {
    return htmlSafe(`background-color: ${ this.get('product.partner.profile_banner_background_color') }`);
  }),

  banner: computed('product.partner.profile_banner', 'isTurbo', function () {
    return this.get('isTurbo') ? null : this.get('product.partner.profile_banner');
  }),

  benefits: computed('isTurbo', 'product.features', 'product.emoticons', function () {
    let benefits;
    let features = this.get('product.features');
    let emoticons = this.get('product.emoticons');

    if (this.get('isTurbo')) {
      benefits = [
        '» No Ads',
        '» Pays broadcasters for invisible ads',
        '» Turbo badge',
        '» Chat emoticons',
        '» More Chat colors',
        '» Increased Storage'
      ];
    } else {
      benefits = [`» ${i18n('Directly supports the broadcaster')}`];

      if (_.contains(features.bitrate_access, 'archives')) {
        benefits.push(`» ${i18n('VOD access')}`);
      }
      if (_.contains(features.bitrate_access, 'live')) {
        benefits.push(`» ${i18n('Higher resolution access')}`);
      }
      if (features.badge) {
        benefits.push(`» ${i18n('Chat badge')}`);
      }
      if (emoticons.length > 0) {
        benefits.push(`» ${i18n('Chat emoticons')}`);
      }
    }
    return benefits;
  }),

  accessStartDate: computed('ticket.access_start', function () {
    let accessStart = this.get('ticket.access_start');

    if (accessStart) {
      let date = new Date(accessStart);
      return date.toString('MMM d, yyyy');
    }
  }),

  accessEndDate: computed('ticket.access_end', function () {
    let accessEnd = this.get('ticket.access_end');

    if (accessEnd) {
      let date = new Date(accessEnd);

      return date.toString('MMM d, yyyy');
    }
  }),

  membershipIncludesTwitchPrime: computed(function (){
    let phrase = i18n('Membership included free with [AmazonPrime logo]');
    let logo = `<img src="https://images-na.ssl-images-amazon.com/images/G/01/sm/landing/amazonprime-logo-white.svg">`;
    return htmlSafe(phrase.replace('[AmazonPrime logo]', logo));
  }),

  actions: {
    toggleBalloon(btnName) {
      if (this.get('openedBalloon') === btnName) {
        this.set('openedBalloon', '');
      } else {
        this.set('openedBalloon', btnName);
      }
    }
  },

  didInsertElement: function () {
    this._initEmoticonCopier();
    this._initTipsy();
  },

  willDestroyElement() {
    this._$emoticons.off('mouseenter');
    this._$emoticons.off('mouseleave');
  },

  _initTipsy: function () {
    $('#global-zeroclipboard-html-bridge').tipsy({gravity: 'n', live: true});
  },

  _initEmoticonCopier: function () {
    this._$emoticons = this.$('.ticket .emoticon-img');
    let clip = new ZeroClipboard(
      this._$emoticons,
      {
        moviePath: '/swf/ZeroClipboard.swf',
        allowScriptAccess: 'always',
        trustedDomains: location.hostname
      }
    );
    let clipOverlay = $('#global-zeroclipboard-html-bridge');
    let zeroHack = {
      didHover: false,
      mouseOver: function () {
        // hack to reposition zeroclipboard on hover after main_col div is scrolled
        let currClipTop = clipOverlay.offset().top;
        let scrollOffset = $('#main_col .tse-scroll-content').scrollTop();
        let newClipTop = currClipTop - scrollOffset;

        if (currClipTop !== newClipTop && !this.didHover) {
          clipOverlay.css('top', newClipTop);
          this.didHover = true;
        }
      },
      mouseOut: function () {
        this.didHover = false;
      }
    };

    this._$emoticons.on('mouseenter', function () {
      clip.setText(this.title);
      clip.glue(this);
      zeroHack.mouseOver();
    });
    this._$emoticons.on('mouseleave', function () {
      zeroHack.mouseOut();
    });

    clip.on('mouseover', function () {
      clipOverlay.attr('title', this.title);
      clipOverlay.tipsy('show');
    });

    clip.on('mouseout', function () {
      clipOverlay.tipsy('hide');
    });

    clip.on('complete', function () {
      let originalEmoteAttr = this.title;
      clipOverlay.attr('title', 'Copied to Clipboard!').tipsy('hide').tipsy('show');
      clipOverlay.attr('title', originalEmoteAttr);
    });
  }
});
