var express = require('express'), fs = require('fs'), sqlite3 = require('sqlite3').verbose();
var EventEmitter = require('events');
var log4js = require('log4js');
var logger = log4js.getLogger();

var router = express.Router();

var EventEmitter = require('events');
var busEmitter = new EventEmitter();


var temp_db;
var file = process.env.DB_HOME + '/' + "temp.db";
var exists;
/* GET users listing. */

function createDB() {
    logger.debug('Creating Temp db...');
    logger.debug(file);
    if (!fs.existsSync(file)) {
        logger.debug('creating db file');
        fs.openSync(file, 'w');

        temp_db = new sqlite3.Database(file, createTable);

        temp_db.close();
    }
    else {
        logger.info('Database already created.');
        connectDB();
    }


}

function startEventHandler() {
    "use strict";

}
function connectDB() {
    "use strict";
    logger.debug('Connect db.');
    temp_db = new sqlite3.Database(file);
    //logger.debug(temp_db);

    return temp_db;
}

function createTable() {
    logger.debug('Creating temp table...');
    temp_db.run('CREATE TABLE IF NOT EXISTS temp (date text, reading real);');
}


function closeDB() {
    "use strict";
    logger.debug('Closing db.');
    temp_db.close();
}

function insertTempReading(time, reading) {
    logger.debug('Inserting reading:' + reading);

    temp_db.run('BEGIN TRANSACTION');
    temp_db.run('INSERT into temp(date, reading) VALUES (?,?);', [time, reading]);
    temp_db.run('commit');
}

/*router.get('/', function (req, res, next) {
 var now = new Date();

 var t = req.query;

 logger.debug('t:');
 logger.debug(JSON.stringify(t));
 if (req.query != {} && req.query.temp != null) {
 // createDB();


 res.writeHead(200, {"ContentType": "text/html"});
 //res.send(JSON.stringify(t));
 res.end('ok');
 } else {
 res.writeHead(200, {"ContentType": "text/html"});
 //res.send(JSON.stringify(t));
 res.end('error?');
 }


 });*/

/*router.get('/:id', function (req, res, next) {
 var id = req.params.id;

 logger.debug('id: ' + id);
 res.writeHead(200, {"ContentType": "text/html"});
 //res.send(JSON.stringify(t));
 res.end('ok');
 });*/

router.get('/', function (req, res, next) {
    res.render('temp');
});


router.post('/', function (req, res, next) {
    "use strict";

    var t = req.body;
    var now = new Date();
    var dataJSON;

    if (t.hasOwnProperty('data')) {
        var data = JSON.parse(t.data.toString());

        if (data.hasOwnProperty('temp')) {
            busEmitter.emit("saveTempData", {time: now.toJSON(), value: parseFloat(data.temp)});
        }
        else {
            logger.error('No temp data!');
        }
    }
    else {
        logger.error('No data block!');
    }

    res.writeHead(200, {"ContentType": "text/html"});
    res.end('ok');
});


router.get('/all', function (req, res, next) {
    "use strict";
    logger.debug('Selecint all..');
    //var db = connectDB();

    temp_db.all('SELECT * from temp', function (err, rows) {

        var out = [];
        logger.debug(err);
        logger.debug(rows);
        rows.forEach(function (row) {
            logger.debug(row.date + ', ' + row.reading);
            //  var t = ;
            //  out.push({"date": Date(row.date), "reading":row.reading});
            out.push({"date": row.date, "reading": row.reading});
        });

        res.writeHead(200, {"ContentType": "application/json"});
        //res.send(JSON.stringify(t));
        res.end(JSON.stringify(out));

        //closeDB();
    });
});

module.exports = router;

createDB();


var sendSocketHandler = (obj) =>{
    //   logger.info('sendSocket: ' + JSON.stringify(obj));
    insertTempReading(obj.time, obj.value);
}
busEmitter.on('saveTempData', sendSocketHandler);
