'use strict';

const httpHelper = require('./helper/httpHelper');

exports.list = function(req, res) {
    
    httpHelper.applyFilter(req, 'list');

    const limit = req.query.limit || 10;

    const page = typeof req.query.page !== 'undefined' ? 
    httpHelper.getPage(req.query.page, limit) : 
    httpHelper.getPage(1, limit);

    let query =	req.schema.find(req.filter).limit(limit).skip(page).lean();
		
    if (typeof req.model.list.populate !== 'undefined' && req.model.list.populate.length > 0) {
        query = httpHelper.addPopulate(query, req.model.list.populate);
    }

    query.select(req.model.list.select || {});
    
    const queryCount = req.model.list.paginate ? req.schema.count(req.filter) : null;

    return Promise.all([query, queryCount])
    .then(function(data) {
        const count = data[1] || null;
        var response = {
            limit: limit,
            docs: data[0]
        };

        if (count) {
            response.pages = Math.ceil(count / limit);
            response.total = count;
        }

        res.send(response);
    })
    .catch(err => res.status(500).send(err));
};

exports.detail = function(req, res) {
    let query =	req.schema.findById(req.params.id).lean();

    if (
        typeof req.model.detail.populate !== 'undefined' && req.model.detail.populate.length > 0) {
        query = httpHelper.addPopulate(query, req.model.list.populate);
    }
	
    query.select(req.model.detail.select || {});
    
    return query
    .then(doc => res.send(doc))
    .catch(err => res.status(500).send(err));
};

exports.create = function(req, res) {
    return	req.schema.create(req.body)
    .then(doc => res.send(doc))
    .catch(err => res.status(500).send(err));
};

exports.update = function(req, res) {
    return	req.schema.findOneAndUpdate({_id: req.params.id }, req.body, {new: true})
    .lean()
    .then(doc => res.send(doc))
    .catch(err => res.status(500).send(err));
};

exports.delete = function(req, res) {
    return req.schema.remove({ _id: req.params.id }).lean()
    .then(doc => res.send(doc))
    .catch(err => res.status(500).send(err));
};

@@ -824,40 +824,35 @@
 a%5B1%5D
- %7C%7C null;%0A        var response =
+;%0A%0A        res.send(count ?
  %7B%0A 
@@ -901,16 +901,17 @@
  data%5B0%5D
+,
 %0A       
@@ -915,61 +915,18 @@
     
-%7D;%0A%0A        if (count) %7B%0A            response.
+    
 pages
- =
+:
  Mat
@@ -946,17 +946,17 @@
 / limit)
-;
+,
 %0A       
@@ -964,31 +964,20 @@
     
-response.
 total
- =
+:
  count
-;
 %0A   
@@ -986,35 +986,41 @@
    %7D
-%0A%0A        res.send(response
+ : %7Blimit: limit, docs: data%5B0%5D %7D
 );%0A 

delete vars to methods