import { JSONAPISerializer } from 'ember-cli-mirage';

import _ from 'lodash';

export default JSONAPISerializer.extend({

  serialize: function (response, request) {

    // Remove models with no name
    response.models = response.models.filter(element => element.label);

    let qParams = request.queryParams['theme'];
    if (qParams) {
      response.models = response.models
        .slice(0, response.models.length / Math.pow(2, qParams.length))
        .map(t => {
          t.count = Math.max(Math.floor(t.count / 2), 1);
          return t;
        });
    }

    let total = response.models.length;

    // Alphabetical order
    if (request.queryParams.sort === 'alphabetical') {
      response.models.sort(function (a, b) {
        var aLabel = a.label.toUpperCase();
        var bLabel = b.label.toUpperCase();
        if (aLabel < bLabel) { return -1; }
        if (aLabel > bLabel) { return 1; }
        return 0;
      });
      // Descending order
    } else if (request.queryParams.sort === 'descending') {
      response.models.sort(function (a, b) {
        return b.count - a.count;
      });
    }
    var array = [];
    if (typeof request.queryParams.index !== 'undefined' && typeof request.queryParams.limit !== 'undefined') {
      var begin = parseInt(request.queryParams.index) * parseInt(request.queryParams.limit) || 0;
      var end = begin + parseInt(request.queryParams.limit);
      array = response.models.slice(begin, end);
    } else {
      array = response.models;
    }
    return {
      themes: _(array).map((theme) => { return [theme.id, { count: theme.count, label: theme.label }]; }).fromPairs().value(),
      meta: {
        total: total
      }
    };
  }

});
