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

  server.get('/clips/top', function ({ clips: clipsSchema }, request) {
    let { channel, cursor, limit } = request.queryParams;

    let clips;

    if (channel) {
      clips = clipsSchema.where((clip) => {
        return clip.broadcaster.login === channel;
      });
    } else{
      clips = clipsSchema.all();
    }

    if (!limit) {
      limit = 10;
    } else {
      limit = parseInt(limit);
    }

    // TODO: support `period` and `trending` params
    clips.sort((clipA, clipB) => {
      // descending order
      return clipB.views - clipA.views;
    });

    // Collections returned by model class methods have the structure:
    // { modelName: 'clip', models: [ ... ] }
    // and don't implement all array methods, so we grab the native array
    let allClipsArray = clips.models;
    let limitedClipsArray;
    let cursorIndex = 0;

    if (cursor) {
      // TODO: phantomjs-polyfill + phantomjs-pollyfill-find-index?
      // cursorIndex = clipsArray.findIndex((clip) => {
      //   return clip.id === cursor;
      // });
      allClipsArray.forEach((clip, index) => {
        if (clip.id === cursor) {
          cursorIndex = index;
        }
      });

      limitedClipsArray = allClipsArray.slice(cursorIndex, cursorIndex + limit);
    } else {
      limitedClipsArray = allClipsArray.slice(0, limit);
    }

    let newCursorIndex = cursorIndex + limit;
    let numberOfClips = allClipsArray.length;

    if (newCursorIndex < numberOfClips) {
      return {
        clips: limitedClipsArray,
        _cursor: allClipsArray[newCursorIndex].id
      };
    }

    return {
      clips: limitedClipsArray
    };
  });
}
