'use strict';

var db = require(__config_path + '/db');
var consts = require(__config_path + '/consts');
var moment = require('moment');

/**
 * Hàm lấy ds phân trang
 *
 * @param input
 * @param callback
 */
exports.getListing = function (input, callback) {
    if (input.page_index < 1) input.page_index = 1;
    var limit = consts.PAGE_SIZE;
    var offset = (input.page_index - 1)*limit;

    let sql = 'SELECT T.* FROM ' + consts.DB_TABLE.TASKS + ' T WHERE T.id > 0 ';

    if (input.key_word != '') {
        sql += ' AND (T.name LIKE "%' + input.key_word + '%" ';
        sql += ' OR T.description LIKE "%' + input.key_word + '%") ';
    }

    if (input.priority != -1) {
        sql += ' AND T.priority = ' + input.priority;
    }

    if (input.status != -1) {
        sql += ' AND T.status = ' + input.status;
    }

    sql += ' ORDER BY created_at DESC ';
    sql += ' LIMIT ' + offset + ',' + limit;

    db.query(sql, [], callback);

}

/**
 * Hàm lấy tổng số bàn ghi theo đk tìm kiếm
 *
 * @param input
 * @param callback
 */
exports.getTotal = function (input, callback) {
    var sql = 'SELECT COUNT(T.id) AS total_record FROM ' + consts.DB_TABLE.TASKS + ' T WHERE T.id > 0 ';

    if (input.key_word != '') {
        sql += ' AND (T.name LIKE "%' + input.key_word + '%" ';
        sql += ' OR T.description LIKE "%' + input.key_word + '%") ';
    }

    if (input.priority != -1) {
        sql += ' AND T.priority = ' + input.priority;
    }

    if (input.status != -1) {
        sql += ' AND T.status = ' + input.status;
    }

    db.query(sql, [], callback);
}

/**
 * Hàm thêm mới 1 task
 *
 * @param data
 * @param callback
 */
exports.store = function (data, callback) {
    let sql = 'INSERT INTO ' + consts.DB_TABLE.TASKS + ' SET ?';
    db.query(sql, {
        name: data.name,
        priority: data.priority,
        description: data.description,
        created_at: moment().format('YYYY-MM-DD HH:mm:ss'),
        updated_at: moment().format('YYYY-MM-DD HH:mm:ss')
    }, callback);
}