import Mirage from 'ember-cli-mirage';
import serialize from 'web-client/mirage/utils/serialize';
import pageParams from 'web-client/mirage/utils/page-params';
import { parseQueryParams } from 'web-client/utilities/url-params';

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

  server.get('/users/:user_login/emotes', function() {
    return { emoticon_sets: [] };
  });

  server.get('/users/:user_login', function (schema, request) {
    let login = request.params.user_login;
    let user = schema.db.users.where({ login })[0];
    if (!user) {
      return new Mirage.Response(404, {}, {
        status: 404,
        error: `user with login '${login}' not found `
      });
    }

    return user;
  });

  server.get('/user', function (schema) {
    let user = schema.db.users[0];
    return user;
  });

  server.get('/user/subscriptions/credit', function () {
    return {
      subscription_credit_balance: 1
    };
  });

  server.get('/users/:user_login/chat/badges', function () {
    return [];
  });

  server.get('/users/:user_login/follows/channels/:channel', function(schema, request) {
    let login = request.params.user_login;
    let channelName = request.params.channel;
    let follow = schema.follows.where({ userName: login, channelName }).models[0];

    if (!follow) {
      return new Mirage.Response(404, {}, {
        status: 404,
        error: `follow '${channelName}' not found `
      });
    }

    return serialize(server, follow);
  });

  server.put('/users/:user_login/follows/channels/:channel', function(schema, request) {
    let login = request.params.user_login;
    let name = request.params.channel;
    let channel = schema.channels.where({ name }).models[0];
    if (!channel) {
      channel = server.create('channel', { name });
    }

    let follow = schema.db.follows.where({ userName: login, channelName: name })[0];

    if (!follow) {
      follow = server.create('follow', {
        userName: login,
        channelName: name,
        channel
      });
    }

    let params = parseQueryParams(request.requestBody);
    params.notifications = params.notifications === 'true';
    schema.db.follows.update(follow, params);
    follow = schema.follows.where({ userName: login, channelName: name }).models[0];

    return serialize(server, follow);
  });

  server.delete('/users/:user_login/follows/channels/:channelName', function({ follows }, { params }) {
    follows.where({ userName: params.user_login, channelName: params.channelName }).destroy();
  });

  server.get('/users/:user_login/follows/channels', function(schema, request) {
    const PAGESIZE = 25;
    let { offset } = pageParams(request);
    let userLogin = request.params.user_login;
    let follows = schema.follows.where({ userName: userLogin });
    let _total = follows.models.length;

    let feature = request.queryParams.feature;
    feature = feature ? `&feature=${feature}` : '';

    let serialized = serialize(server, follows);
    serialized = serialized.slice(offset, offset + PAGESIZE);

    return {
      follows: serialized,
      _total,
      _links: {
        self: `https://api.twitch.tv/kraken/users/${userLogin}/follows/channels?direction=DESC&limit=${PAGESIZE}&offset=${offset}&sortby=created_at${feature}`,
        next: `https://api.twitch.tv/kraken/users/${userLogin}/follows/channels?direction=DESC&limit=${PAGESIZE}&offset=${offset + PAGESIZE}&sortby=created_at${feature}`
      }
    };
  });

 server.del('users/:user_login/friends/notifications', () => {
    return { requests: [] };
  });

  server.get('users/:user_login/friends/notifications', function() {
    return { count: 0 };
  });

  server.get('users/:user_login/friends/requests', function(schema, request) {
    let user = schema.db.users.where({ login: request.params.user_login })[0];
    let requests = schema.db.friendRequests.where({ targetId: user._id });

    let serializedRequests = requests.map((friendRequest) => {
      return {user: schema.db.users.where({ _id: parseInt(friendRequest.senderId, 10) })[0]};
    });

    return { requests: serializedRequests, _total: serializedRequests.length };
  });

  server.get('users/:user_login/friends/recommended', function(schema) {
    return schema.friendsListUsers.all();
  });

  server.get('users/:user_login/friends/:friend_name', function(schema, request) {
    // TODO make tests pass even if not friends with user
    // {
    //   error: 'Unauthorized',
    //   message: 'Token invalid or missing required scope',
    //   status: 401
    // };

    let user = schema.db.users.where({ name: request.params.friend_name })[0];
    if (!user) {
      user = { _id: 'u1' };
    }

    return { friends: false, status: 'no_relation', user };
  }, 200);

  server.get('/users/:user_login/blocks', function() {
    return { blocks: [] };
  });

  /**
   * /api endpoints
   */
  server.namespace = 'http://api.twitch.tv/api';

  server.get('users/:user_login/followed/hosting', function (schema) {
    return schema.hosts.all();
  });

  server.get('users/:user_login/follows/games', function (schema) {
    return schema.gameFollows.all();
  });

  server.put('users/:user_login', function(schema, request) {
    let user = schema.users.where({ login: request.params.user_login }).models[0];
    if (!user) {
      return new Mirage.Response(404, {}, {
        status: 404,
        error: `user '${name}' not found `
      });
    }

    let body = parseQueryParams(request.requestBody);
    user.update(body);
    return user.reload().attrs;
  });

  server.get('users/:user_login/follows/games/live', function (schema) {
    return schema.gameFollows.all();
  });

  server.put('users/:user_login/follows/games/follow', (schema, request) => {
    let body = parseQueryParams(request.requestBody);
    let game = schema.games.where({ name: body.name }).models[0];
    schema.create('game-follow', {gameId: game.id});

    return game;
  });

  server.delete('users/:user_login/follows/games/unfollow', (schema, request) => {
    let body = parseQueryParams(request.requestBody);
    let game = schema.games.where({ name: body.name }).models[0];
    let follow = schema.gameFollows.where({ gameId: game.id });

    follow.destroy();
    return game;
  });

  server.get('/users/:user_login/tickets', function () {
    return { tickets: [] };
  });

  server.get('/users/:user_login/related_videos', function () {
    return {};
  });

  server.get('/users/:user_login/follows/games/isFollowing', function (schema, request) {
    let name = request.queryParams.name;
    let game = schema.games.where({ name }).models[0];
    let follows = schema.gameFollows.where({ gameId: game.id });

    if (follows.models.length) {
      return game;
    }

    return new Mirage.Response(404, {}, {
      status: 404,
      error: 'Not Found',
      message: "isn't following"
    });
  });

  server.namespace = null;
}
