import Component from 'ember-component';
import computed from 'ember-computed';
import { assert } from 'ember-metal/utils';
import {
  facebookShareLink,
  twitterShareLink,
  redditShareLink
} from 'web-client/utilities/social-links';
import { translationMacro as t } from 'ember-intl';
import { withQueryParams } from 'web-client/utilities/url-params';
import injectService from 'ember-service/inject';

export const FACEBOOK_SHARE_MEDIUM = 'fb';
export const TWITTER_SHARE_MEDIUM = 'twtr';
export const REDDIT_SHARE_MEDIUM = 'redt';

export function withMediumTrackingParams(url, medium) {
  return withQueryParams(url, ['tt_medium'], { tt_medium: medium });
}

let ClipShareBox = Component.extend({
  classNames: ['flex flex--nowrap'],
  attributeBindings: ['testSelector:data-test-selector'],
  testSelector: 'clips-share-box',

  intl: injectService(),

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

    assert('{{clip-share-box}} expects parameter "clip"', !!this.get('clip'));
  },

  shareCaption: computed('clip.title', 'defaultShareCaption', function () {
    let title = this.get('clip.title');

    if (title) {
      return title;
    }

    return this.get('defaultShareCaption');
  }),

  defaultShareCaption: t('channel.clips.clip.share.defaultMessage', {
    broadcaster: 'clip.broadcasterDisplayName'
  }),

  facebookShareLink: computed('clip.url', function () {
    let clipURL = withMediumTrackingParams(this.get('clip.url'), FACEBOOK_SHARE_MEDIUM);

    return facebookShareLink(clipURL);
  }),

  twitterShareLink: computed('clip.url', 'shareCaption', function () {
    let clipURL = withMediumTrackingParams(this.get('clip.url'), TWITTER_SHARE_MEDIUM);
    let title = this.get('shareCaption');

    return twitterShareLink(clipURL, title);
  }),

  redditShareLink: computed('clip.url', 'shareCaption', function () {
    let clipURL = withMediumTrackingParams(this.get('clip.url'), REDDIT_SHARE_MEDIUM);
    let title = this.get('shareCaption');

    return redditShareLink(clipURL, title);
  }),

  actions: {
    selectCopyLink() {
      this.$('.js-copy-link').select();
    }
  }
});

ClipShareBox.reopenClass({
  positionalParams: ['clip']
});

export default ClipShareBox;
