// mirage/serializers/blog-post.js
import BaseSerializer from './application';
import _ from 'lodash';
import utils from './utils';

export default BaseSerializer.extend({
    attrs: ['id', 'title', 'languages', 'url', 'issued', 'modified', 'publishers', 'mediaArray', 'transcript'],

    serialize(response, request) {
        // This is how to call super, as Mirage borrows [Backbone's implementation of extend](http://backbonejs.org/#Model-extend)
        let json = BaseSerializer.prototype.serialize.apply(this, arguments);

        if(request.queryParams.id) {
            let docs = _(json['documents']).filter(function(m) {
                return m.id === request.queryParams.id;
            }).map(function(doc) {
                let res = _.omit(doc, ['publishers', 'mediaArray', 'transcript']);
                res['publisher'] = doc['publishers'].join(', ');
                res['duration_ms'] = doc['mediaArray']?doc['mediaArray'][_(Object.keys(doc['mediaArray'])).first()]['extent_ms']:0;
                res['transcript_url'] = (doc['transcript'] && doc['transcript']['url'])?doc['transcript']['url']:null;
                return res;
            }).value();
            let meta = {
              total: 1,
              per_page: 1,
              current_page: 1,
              last_page: 1,
              from: 1,
              to: 1,
              prev_page_url: null,
              next_page_url: null
            };

            return {'documents': docs, 'meta': meta};
        }

        let page = Math.max(parseInt(request.queryParams.page || 1) - 1, 0);
        let perPage = parseInt(request.queryParams.perpage || 100);

        json['documents'] = _.map(_.slice(json['documents'], page*perPage, (page+1)*perPage), function(doc) {
            let res = _.omit(doc, ['publishers', 'mediaArray', 'transcript']);
            res['publisher'] = doc['publishers'].join(', ');
            res['duration_ms'] = doc['mediaArray']?doc['mediaArray'][_(Object.keys(doc['mediaArray'])).first()]['extent_ms']:0;
            res['transcript_url'] = (doc['transcript'] && doc['transcript']['url'])?doc['transcript']['url']:null;
            return res;
        });

        let meta = {
          total: response.models.length,
          per_page: perPage,
          current_page: page+1,
          last_page: Math.floor(response.models.length/perPage)+1,
          from: page*perPage + 1,
          to: Math.min((page+1)*perPage, response.models.length),
          prev_page_url: null,
          next_page_url: null
        };

        let urlParts = utils.parseUri(request.url);

        if(page>0) {
          let prevUrlParts = _.clone(urlParts);
          prevUrlParts.queryKey.page = page;
          meta.prev_page_url = utils.mergeUri(prevUrlParts);
        }

        if(page<(meta.last_page-1)) {
          let nextUrlParts = _.clone(urlParts);
          nextUrlParts.queryKey.page = page+2;
          meta.next_page_url = utils.mergeUri(nextUrlParts);
        }

        json['meta'] = meta;

        return json;
    }

});

// total	3373
// per_page	15
// current_page	1
// last_page	225
// next_page_url	"http://localhost:8000/api/v1/documents?page=2"
// prev_page_url
// from	1
// to	15
