import Service from 'ember-service';
import injectService from 'ember-service/inject';
import computed from 'ember-computed';
import { assert } from 'ember-metal/utils';
import { isPresent } from 'ember-utils';
import { camelize } from 'ember-string';

const RESPONSE_KEYS = [
  "broadcaster_channel_url",
  "broadcaster_display_name",
  "broadcaster_id",
  "clip_url",
  "created_at",
  "curator_channel_url",
  "curator_display_name",
  "curator_id",
  "game",
  "preview_image",
  "thumbnails",
  "title"
];

export default Service.extend({
  ajax: injectService('twitch-clips/backend/ajax'),
  experiments: injectService(),
  storage: injectService(),
  session: injectService(),

  /**
  * Fetch information about a Clip.
  *
  * Example Response:
  * {
  *   "broadcaster_channel_url": "https://www.twitch.tv/taketv",
  *   "broadcaster_display_name": "TaKeTV",
  *   "broadcaster_id": "30186974",
  *   "clip_url": "https://clips.twitch.tv/taketv/WittyGrouseBrainSlug",
  *   "created_at": "2016-06-24 22:03:50.297394976 +0000 UTC",
  *   "curator_channel_url": "https://www.twitch.tv/calebaracous",
  *   "curator_display_name": "CalebAracous",
  *   "curator_id": "31211723",
  *   "game": "StarCraft II",
  *   "preview_image": "https://clips-media-assets.twitch.tv/22002434432-index-0000010505-preview.jpg",
  *   "thumbnails": {
  *       "tiny": "https://clips-media-assets.twitch.tv/22002434432-index-0000010505-preview-86x45.jpg"
  *   },
  *   "title": "HSCXIII powered by MIFcom  - Day 2 starts at 2pm CEST"
  * }
  */
  getClipInfo(slug) {
    const endpoint = `/clips/${slug}`;
    return this.get('ajax').request(endpoint).then(response => {
      let camelizedResponse = {};

      Object.keys(response).forEach(key => {
        if (RESPONSE_KEYS.includes(key)) {
          camelizedResponse[camelize(key)] = response[key];
        }
      });

      return camelizedResponse;
    });
  },

  // Clips Tab on Game Dir Experiment
  isClipsTabOnGameDirEnabled: false,
  checkClipsTabOnGameDirExperiment() {
    return this.get('experiments').getExperimentValue('CLIPS_HEAR_ME_NOW').then(value => {
      if (this.isDestroyed) { return; }
      this.set('isClipsTabOnGameDirEnabled', value === 'variant1');
    });
  },

  // Clips on Game Directory Page Upsell
  shouldShowGameUpsell: computed.not('storage.clipsGameNavCTADismissed'),
  dismissGameUpsell() {
    this.get('storage').set('clipsGameNavCTADismissed', true);
  },

  // Clips Tab Experiment
  hasCheckedExperiment: false,
  isClipsTabEnabled: false,
  checkClipsTabExperiment() {
    if (this.get('hasCheckedExperiment')) {
      return;
    }

    this.set('hasCheckedExperiment', true);
    return this.get('experiments').getExperimentValue('CLIPS_FEEL_IT_COMING').then(value => {
      if (this.isDestroyed) { return; }
      this.set('isClipsTabEnabled', value === 'variant1');
    });
  },

  // Clips on Channel Page Upsell
  shouldShowUpsell: computed.not('storage.clipsNavCTADismissed'),
  dismissUpsell() {
    this.get('storage').set('clipsNavCTADismissed', true);
  },

  reportClip(slug, reason, description) {
    const endpoint = `https://clips.twitch.tv/${slug}/report`;
    const params = `description=${encodeURIComponent(description)}&reason=${reason}`;
    const endpointWithParams = `${endpoint}?${params}`;

    let options = {
      method: 'POST',
      headers: {}
    };

    return this.get('session').getOAuthToken().then(token => {
      if (token) {
        options.headers.Authorization = `OAuth ${token}`;

        return this.get('ajax').request(endpointWithParams, options);
      }

      assert(`Missing a OAuth2 token`, isPresent(token));
    });
  },

  removeClipRecord(slug) {
    // If the provided URL is deemed to be a complete URL, ember-ajax ignores host and namespace
    const endpoint = `https://clips.twitch.tv/${slug}/remove`;
    let options = {
      method: 'DELETE',
      headers: {}
    };

    return this.get('session').getOAuthToken().then(token => {
      if (token) {
        options.headers.Authorization = `OAuth ${token}`;

        return this.get('ajax').request(endpoint, options);
      }

      assert(`Missing a OAuth2 token`, isPresent(token));
    });
  }
});
