import Service from 'ember-service';
import injectService from 'ember-service/inject';
import { normalizeVideoId } from 'web-client/utilities/normalize-video-id';

/*
  Vod-Appeals Service.

  Responsible for getting and creating vod appeals and getting muted tracks.

  Also loads the Bits parsing configuration and provides helper methods for use in parsing Bits messages.
*/

export default Service.extend({
  api: injectService(),

  /* getMutedTracks example response:
  { muted_tracks: [
    {
      "id":"47507737",
      "title":"We Will Rock You (1993 Remastered Version)",
      "performer":"Queen",
      "offset":0,
      "duration":180,
      "is_muted":true,
      "track_appeal":null
    },
    {
      ...
      "track_appeal": {
        "status": "pending",
        "reason": "permission_rights",
      }
    }
  ]}
*/
  getMutedTracks(prefixedVodId) {
    let vodId = normalizeVideoId(prefixedVodId);
    return this.get('api').request('get', `/api/vods/${vodId}/muted_tracks`).then(data => {
      return data.muted_tracks;
    });
  },

  /* createAppeal example input:
  {
    "track_appeals": [
      {
        "audible_magic_response_id": "7507737",
        "reason": "original_content",
      }, {
        "audible_magic_response_id": "7507738",
        "reason": "permission_rights",
      }
    ],
    "full_name": "asdf",
    "street_address_1": "adsf",
    "country": "asdf",
    "city": "asdf"
  }
*/
  createAppeal(prefixedVodId, appeal) {
    let vodId = normalizeVideoId(prefixedVodId);
    return this.get('api').request('post', `/api/vods/${vodId}/appeal`, JSON.stringify(appeal), {
      secure: true,
      contentType: 'application/json'
    });
  },

  /* getVodAppeals example response:
  { vod_appeals: [
    {
      "vod_id":3744954,
      "is_muted":true,
      "can_create_appeal":true,
      "can_view_appeal":false,
      "has_pending_appeal":false
    }
  ]}
*/

  getVodAppeals(vodId) {
    return this.get('api').request('get', `/api/vods/${vodId}/vod_appeals`).then(data => {
      return data.vod_appeals;
    });
  },

  getVodAppeal(prefixedVodId) {
    let vodId = normalizeVideoId(prefixedVodId);
    return this.getVodAppeals(vodId).then((appeals) => {
      let appeal = appeals && appeals[0];
      if (appeal) {
        return appeal;
      }
      throw new Error(`Expected appeal in ${appeals}, got none`);
    });
  }
});
