var mysql = require('mysql');

class database {
    constructor() {
        this._user = '';
        this._password = '';
        this._host = '';
        this._port = 3306;
        this._database = '';
        this._socketPath = '/var/lib/mysql/mysql.sock'
        this._con = null;
        this.autoclose = false;
    }

    connect() {
        if (!this._user || !this._host || !this._password || !this._database) throw 'mysql connect arg is empty';
        this._con = mysql.createConnection({
            user: this._user,
            password: this._password,
            host: this._host,
            database: this._database,
            port: this._port,
            socketPath: this._socketPath
        });
    }

    checkConnect() {
        if (!this._con) {
            this.connect();
        }
    }

    formatQuery(query, arg) {
        return mysql.format(query, arg);
    }

    escape(val) {
        return mysql.escape(val);
    }

    query(query, params, cb) {
        this.checkConnect();
        let self = this;
        if (typeof params == 'function') {
            cb = params;
            params = [];
        };
        if (typeof params == 'object' && !Array.isArray(params)) params = [];

        this._con.query(query, params, (err, rows, field) => {
            if (self.autoclose) {
                self.close(() => {
                    cb.apply(this, [err, rows, field]);
                });
            } else {
                cb.apply(this, [err, rows, field]);
            }
        });
    }

    recordPage(rows, page, maxPage) {
        if (!page || !isFinite(page) || page < 1) page = 1;

        let totalpage = Math.ceil(rows / maxPage);

        let prevpage = page - 1;
        let nextpage = page + 1;

        if (prevpage < 1) prevpage = 1;
        if (nextpage > totalpage) nextpage = totalpage;

        let rec_start = (page - 1) * maxPage + 1
        let rec_end = (rec_start + maxPage - 1);
        if (rec_end > rows) rec_end = rows;

        let json = {
            rec_start,
            rec_end,
            total: rows,
            prevpage,
            nextpage,
            totalpage,
            page
        };

        return json;
    }

    close(cb) {
        let self = this;
        this._con.end((err) => {
            self._con = null;
            if (cb) cb();
        });
    }

    set user(str) { this._user = str; }
    set host(str) { this._host = str; }
    set password(str) { this._password = str; }
    set port(str) { this._port = str; }
    set database(str) { this._database = str; }
}

module.exports = database;