'use strict';

var async = require('async');
var moment = require('moment');
var utils = require(__libs_path + '/utils');
var consts = require(__config_path + '/consts');
var Task = require('../models/task.model');

/**
 * Hàm hiển thị form ds task
 *
 * @param req
 * @param res
 * @param next
 */
exports.showList = function(req, res, next) {
    res.render('pages/task/index', {
        title: 'Task list'
    });
}

/**
 * Hàm xử lý thêm mới một task
 *
 * @param req
 * @param res
 * @param next
 */
exports.store = function (req, res, next) {
    var name = req.body.name;
    var priority = req.body.priority;
    var description = req.body.description;

    console.log(req.body.description);

    async.waterfall([
        function (cb) {
            Task.store({name: name, priority: priority, description: description}, function (err, res) {
                if (err) return cb(err);
                cb(null, res);
            })
        }
    ], function (err, result) {
        console.log(result);

        res.json({
            code: 200,
            message: 'OK',
            data: null
        })
    });
}

/**
 * Hàm xử lý tìm kiếm theo ajax
 *
 * @param req
 * @param res
 * @param next
 */
exports.ajaxList = function (req, res, next) {
    var key_word = req.body.key_word;
    var priority = parseInt(req.body.priority || -1);
    var status = parseInt(req.body.status || -1);
    var page_index = parseInt(req.body.page_index || 1);

    var input = {
        key_word: key_word,
        priority: priority,
        status: status,
        page_index: page_index
    };

    async.waterfall([
        function (cb) {
            Task.getTotal(input, function (err, res) {
                if (err) return cb(err);
                if (res[0].hasOwnProperty('total_record')) {
                    cb(null, res[0].total_record);
                } else {
                    cb(null, 0);
                }
            })
        },
        function (total_record, cb) {
            Task.getListing(input, function (err, res) {
                if (err) return cb(err);
                cb(null, {res:res, total_record:total_record});
            })
        }
    ], function (err, result) {
        res.render('pages/task/partials/ajax_list', {
            data: result.res,
            pagination: utils.genPaginationLink(result.total_record, consts.PAGE_SIZE, page_index),
            order_number: (page_index - 1)*consts.PAGE_SIZE,
            moment: moment,
            getPriorityName: utils.getPriorityName,
            getStatusName: utils.getStatusName
        });
    });
}


exports.delete = function (req, res, next) {
    console.log(req.body.id);
}