import Component from 'ember-component';
import injectService from 'ember-service/inject';
import computed from 'ember-computed';
import { EMOTICONS_V1_URL } from 'web-client/utilities/urls/static-cdn';
import { generateClipsURL } from 'web-client/utilities/clips/clips-url';
import { styledI18n } from 'web-client/helpers/styled-i18n';

// Exported for tests
export const NOTLIKETHIS_IMAGE = `${EMOTICONS_V1_URL}/58765/2.0`; // 2x scale of NotLikeThis

const CLIPS_404_PREVIEW_TINY = 'https://clips-media-assets.twitch.tv/404-preview-86x45.jpg';
const DEFAULT_TITLE = "%{broadcaster} streaming %{game}";
const CREATIVE_TITLE = "%{broadcaster} being Creative"; // Hard code Creative for now

/**
 * Clip Card component.
 * Renders a small preview for Clips given slug data.
 *
 * Attributes:
 *  - broadcasterLogin: login of the Clip's broadcaster
 *  - slug: slug value unique to a Clip's mediakey and curator
 */
export default Component.extend({
  clips: injectService(),
  layout: injectService(),

  broadcasterLogin: '',
  channelLogin: '',
  slug: '',
  clipInfo: null,
  fallbackImage: CLIPS_404_PREVIEW_TINY,

  isLoading: false,
  isErrored: false,
  isChatDark: computed.or('isDarkMode', 'layout.isTheatreMode'),
  init() {
    this._super(...arguments);
    let slug = this.get('slug');

    if (!slug) {
      this.set('isErrored', true);
      return;
    }

    this.set('isLoading', true);
    this.get('clips').getClipInfo(slug).then(clipInfo => {
      if (this.isDestroyed) { return; }

      this.set('clipInfo', clipInfo);
    }, () => {
      if (this.isDestroyed) { return; }

      this.set('isErrored', true);
    }).finally(() => {
      if (this.isDestroyed) { return; }

      this.set('isLoading', false);
    });
  },

  clipsUrl: computed('slug', function () {
    let slug = this.get('slug');
    return generateClipsURL(slug);
  }),

  cardPreviewImage: computed('clipInfo.thumbnails.tiny', function () {
    let clipPreviewImage = this.get('clipInfo.thumbnails.tiny');
    return clipPreviewImage ? clipPreviewImage : NOTLIKETHIS_IMAGE;
  }),

  cardTitle: computed('clipInfo.{broadcasterDisplayName,game,title}', function () {
    let game = this.get('clipInfo.game');
    let broadcaster = this.get('clipInfo.broadcasterDisplayName');
    let title = this.get('clipInfo.title');

    if (title) {
      return title;
    } else if (game === 'Creative') {
      return styledI18n(CREATIVE_TITLE, { broadcaster });
    }
    return styledI18n(DEFAULT_TITLE, { broadcaster, game });
  })
});
