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

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

  server.get('/channels/:channel/payout_entity', function () {
    return {};
  });

  server.get('channels/:channelName/video_manager', function ({ videoManagerProperties }) {
    return videoManagerProperties.first() || {};
  });

  server.get('channels/:username/video_manager/past_broadcasts', function (schema) {
    return schema.videos.all();
  });

  server.get('channels/:username/video_manager/highlights', function({ videos }) {
    return videos.where({ broadcast_type: HIGHLIGHT_TYPE_PARAM });
  });

  server.get('channels/:channelName/revenue', {
      sub_data: [
        {
            recognized_on: '2016-10-14T22:34:40.115204Z',
            gross: 146207,
            net_revenue: 134036,
            partner_revenue: 107228.0
        },
        {
            recognized_on: '2016-10-15T23:53:01.668249Z',
            gross: 143213,
            net_revenue: 131445,
            partner_revenue: 105156.0
        }
      ],
      ad_data: [
        {
            report_date: '2016-10-14T07:00:00Z',
            opportunities: 37062,
            impressions: 37062,
            net_revenue: 77310.48,
            partner_est_cpm: 349.15204,
            partner_revenue: 38655.0,
            turbo_impressions: 10034
        },
        {
            report_date: '2016-10-15T07:00:00Z',
            opportunities: 86730,
            impressions: 86730,
            net_revenue: 210937.47,
            partner_est_cpm: 365.1009,
            partner_revenue: 105468.0,
            turbo_impressions: 17825
        }
      ],
      bits_onboarded: true,
      bits_data: [
        {
            date: '2016-10-14T19:00:00Z',
            bits: 300,
            cents: 300.0
        },
        {
            date: '2016-10-15T16:00:00Z',
            bits: 500,
            cents: 500.0
        }
      ],
      other_data: [
        {
            recognized_on: '2016-10-14T22:15:42.236422Z',
            gross: 67365,
            net_revenue: 67365,
            partner_revenue: 53892.0
        },
        {
            recognized_on: '2016-10-15T22:19:22.282362Z',
            gross: 73852,
            net_revenue: 73852,
            partner_revenue: 59081.0
        }
      ]
  });

  server.get('channels/:channelName/subscriptions', function() {
    return {
      twitch_subscriptions: [{
        sub_date: '2016-10-15T00:00:00Z',
        partner_id: 23161357,
        partner_id_day: '23161357_2016-10-15',
        partner_id_month: '23161357_2016-10',
        login: 'lirik',
        active_subscriptions: 8574,
        day_subscriptions: 287,
        new_subscriptions: 29,
        ended_subscriptions: 0
      }],
      prime_subscriptions: [{
        sub_date: '2016-10-15T00:00:00Z',
        partner_id: 23161357,
        partner_id_day: '23161357_2016-10-15',
        partner_id_month: '23161357_2016-10',
        login: 'lirik',
        active_subscriptions: 5468,
        day_subscriptions: 148,
        new_subscriptions: 148,
        ended_subscriptions: 0
      }]
    };
  });

  server.get('channels/:channel/subscriber_count', { count: 5 });

  server.post('channels/:channelName/subscriber_emails', {
    message: "Emails being sent to subscribers"
  });

  server.post('channels/:channelName/subscriber_list_email', {
    message: "Email being sent to test@testemail.com"
  });

  server.get('channels/:channelName/teespring_campaigns', function (schema, request) {
    if (request.params.channelName === 'baz') {
      return [];
    }
      return [
        {
          campaign_url: 'http://campaign_url_0',
          image_url: 'http://image_url_0',
          name: 'Campaign 0',
          revenue: 10000
        },
        {
          campaign_url: 'http://campaign_url_1',
          image_url: 'http://image_url_1',
          name: 'Campaign 1',
          revenue: 20000
        },
        {
          campaign_url: 'http://campaign_url_2',
          image_url: 'http://image_url_2',
          name: 'Campaign 2',
          revenue: 30000
        }
      ];
  });

  server.get('/featured_games', function (schema) {
    return schema.db.featuredGames;
  });

  server.get('/ticket_products/:channel', function ({ticketProducts}, request) {
    let channel = request.params.channel;
    let product = ticketProducts.where({name: channel}).models[0];
    return product;
  });

  server.post('/ticket_products/:channel', function ({ticketProducts}, request) {
    let channel = request.params.channel;
    let product = ticketProducts.where({name: channel}).models[0];

    /* Twitch.api sends data as URL params instead of JSON without processData: false */
    let params = parseQueryParams(request.requestBody);

    product.net_payment_amendment = params.net_payment_amendment;
    return product.save();
  });

  server.put('/ticket_products/:id', function ({ticketProducts}, request) {
    let id = request.params.id;
    let product = ticketProducts.where({ id }).models[0];

    /* Twitch.api sends data as URL params instead of JSON without processData: false */
    let params = parseQueryParams(request.requestBody);
    product.net_payment_amendment = params.net_payment_amendment;
    return product.save();
  });

  server.get('/channels/:channel/payout_entity', function () {
    return {
      individual_partner: true
    };
  });

  server.get('/payouts/get_tipalti_url', function () {
    return {
      src: ""
    };
  });

  server.get('/payouts/is_payee_payable', function () {
    return {
      payable: true
    };
  });

  server.get('/channels/:channel/panels', function () {
    return [];
  });

  server.post('/channels/:channel/panels', function () {
    // In pre-Ember 2.10, this mock returned no id, causing destroyPanel to be called in the panels test.
    // A bug in pre-Ember 2.10, that destroyPanel did not cause panels.length to change in panels-list.js
    // Changing this to have an id exercises the correct code path in the test.
    return { _id: 'fake' };
  });

  server.get('/channels/:channel/viewer', function (schema) {
    return schema.db.channelViewers[0];
  });

  server.get('/viewer/token.json', function () {
    return {
      status: 401,
      error: 'Not logged in'
    };
  });

  server.get('/viewer/info.json', function () {
    return {
      geo: "US",
      ip: "10.255.247.75",
      preferred_language: "en-US",
      received_language: "en",
      eu: false,
      ad_free_promotion_ad_title: null,
      seconds_to_global_broadcast: -88050459,
      connect_to_host_telegraph: true
    };
  });

  server.get('/channels/:channel/chat_properties', function (schema) {
    return schema.db.channelChatProperties[0];
  });

  server.get('/channels/:channel/ember', function (schema, request) {
    let name = request.params.channel;
    let mirage404 = new Mirage.Response(404, {}, {
      status: 404,
      error: `channel '${name}' not found `
    });

    if (name === '404') {
      return mirage404;
    }

    let channel = schema.db.channelEmberData.where({ name })[0] || schema.channels.where({ name }).models[0];
    return channel ? channel : new Mirage.Response(404, {}, { status: 404, error: `channel '${name}' not found ` });
  });

  server.get('/channels/:channel', function (schema, request) {
    let name = request.params.channel;
    let channel = schema.db.channelEmberData.where({ name })[0];
    return channel ? channel : new Mirage.Response(404, {}, { status: 404, error: `channel '${name}' not found ` });
  });

  server.get('/creative/tags', function () {
    return {
      tags: [
        { tag: 'programming' }
      ]
    };
  });

  server.get('/cs/maps', function () {
    return {
      _total: 2,
      maps: [
        {
          "map": "de_safehouse",
          "map_name": "Safehouse",
          "map_img": "http://cloud-4.steamusercontent.com/ugc/884099387636187794/C4716485D879B70B8C8638936D10CC5C3718E933/200x112.resizedimage",
          "viewers": 0
        }
      ]
    };
  });

  server.get('/cs', function (schema) {
    let streams = schema.db.channelStreams.where({ name: 'Counter-Strike: Global Offensive' });

    return {
      streams
    };
  });

  server.get('/me', function (schema) {
    let user = schema.db.sessionUsers.where({ _is_signed_in_: true })[0];
    if (!user) {
      return new Mirage.Response(401, {}, {
        status: 401,
        error: 'unauthorized'
      });
    }

    // mirage stores IDs as strings but app expects user ID as int.
    user.id = parseInt(user.id, 10);
    return user;
  });

  server.get('/notifications', function () {
    return {};
  });

  server.get('/channels/:channel/product', function (schema, request) {
    let name = request.params.channel;
    return schema.db.products.where({ name })[0] || {};
  });

  server.get('/friendships/users', function (schema, request) {
    let ids = request.queryParams.ids;
    if (ids) {
      ids = ids.split(',');
      return schema.friendshipUsers.where(friendshipUser => ids.includes(friendshipUser.id));
    }
    return schema.friendshipUsers.all();
  });

  server.get('/videos/:video', function ({ videos }, request) {
    let id = normalizeVideoId(request.params.video);
    return videos.find(id);
  });

  server.get('/premium/offers', function (schema) {
    let offers = schema.db.offers;
    if (!schema.db.offers.length) {
      offers = [];
    }
    return { offers };
  });

  server.post('/premium/credit/spend', function () {
    return { subscription_credit_balance: 0 };
  });

  server.get('/resumewatching/user', function (schema) {
    let watchedVideos = schema.watchedVideos.all().models;
    return { videos: watchedVideos };
  });

  server.get('/vods/recommended', function (schema) {
    return schema.videos.all();
  });

  server.get(`/vods/:video/vod_appeals`, function(vodAppeals , request) {
    let id = request.params.video;
    let resp = { vod_appeals: [
      {
        vod_id: id,
        is_muted: true,
        can_create_appeal: true,
        can_view_appeal: false,
        has_pending_appeal: false
      }
    ]};
    return resp;
  });

  server.get(`/vods/:video/muted_tracks`, function(mutedTracks, request) {
    let id = normalizeVideoId(request.params.video);
    let resp = { muted_tracks: [
      {
        id: id,

        title: 'We Will Rock You (1993 Remastered Version)',
        performer: 'Queen',
        offset: 0,
        duration: 180,
        is_muted: true,
        track_appeal: {
          status: 'pending',
          reason: 'permission_rights'
        }
      }
    ]};
    return resp;
  });

  server.post('/vods/:video_id/appeal', function(schema, request) {
    let body = request.requestBody;
    let resp = {
      ok: true
    };

    try {
      JSON.parse(body);
    } catch(e) {
      return false;
    }
    return resp;
  });

  server.namespace = undefined;
}
