import Mirage from 'ember-cli-mirage';
import { assign } from 'ember-platform';
import serialize from 'web-client/mirage/utils/serialize';
import { parseQueryParams } from 'web-client/utilities/url-params';
import { normalizeVideoId } from 'web-client/utilities/normalize-video-id';
import { HIGHLIGHT_TYPE_PARAM } from 'web-client/utilities/video/types';

export default function(server) {
  server.namespace = 'http://api.twitch.tv/kraken';

  server.get('/videos/top', function ({ videos }) {
    let topVideos = [];
    videos.all().models.forEach((video) => {
      let serializedChannel = serialize(server, video.channel).channel;
      topVideos.push(assign(assign({}, video.attrs), {channel: serializedChannel}));
    });

    return {
      videos: topVideos,
      _links: {
        next: "http://api.twitch.tv/kraken/videos/top?limit=2&offset=2",
        self: "http://api.twitch.tv/kraken/videos/top?limit=2&offset=0"
      }
    };
  });

  server.get('/videos/followed', function ({ videoFollows }) {
    return videoFollows.all();
  });

  server.get('/videos/:videoId', function ({ videos }, request) {
    let videoId = request.params.videoId;
    let isAPIv5 = request.requestHeaders['Accept'] === 'application/vnd.twitchtv.v5+json';

    if (!isAPIv5 && videoId[0] !== 'v') {
      throw new Error("Non 'v' prefixed Video ID's aren't supported until v5");
    }

    videoId = normalizeVideoId(videoId);

    if (videoId === '404') {
      return new Mirage.Response(404, {}, {
        status: 404,
        error: "Not Found",
        message: "Video does not exist"
      });
    }

    return videos.find(videoId);
  });

  server.post('/videos/:id/highlight', function(schema, request) {
    let body = parseQueryParams(request.requestBody);

    // Set broadcast_id on highlight to be the same as the original video
    let originalVideoId = request.params.id;
    let originalVideo = schema.videos.where({ id: originalVideoId }).models[0];
    body.broadcast_id = originalVideo.broadcast_id;

    let name = originalVideo.channel.name;
    body.channel = schema.channels.where({ name }).models[0];
    body.length = parseInt(body.end_time) - parseInt(body.start_time);
    body.broadcast_type = HIGHLIGHT_TYPE_PARAM;
    let video = schema.videos.create(body);
    return {
      api_id: video._id,
      url: `https://www.twitch.tv/${body.channel.name}/v/${video.id}`,
      embed_player: `<object>Watch ${body.channel.name} video ${video._id} on twitch</object>`
    };
  });

  server.get('/vods/:videoId/download', function({ videos }, request) {
    let videoId = request.params.videoId;
    let video = videos.find(videoId);

    if (!video) {
      return new Mirage.Response(404, {}, {});
    }

    if (video.videoDownload) {
      return video.videoDownload;
    }

    let download = server.create('video-download');
    video.videoDownload = download;
    video.save();

    return download;
  });

  server.namespace = undefined;
}
