var express     = require('express');
var path        = require('path');
var bodyParser  = require('body-parser');
var q           = require('q');
var router      = express.Router();
var printer     = require('printer');
var db          = require('../../lib/db');
var jobWatcher  = require('./job_watcher');

router.get('/', function(req, res) {
  res.send({status:true});
});

router.get('/list', function(req, res) {
	res.send({status:true, printers: printer.getPrinters()});
});

router.post('/printers', function(req, res) {
	res.send({status:true, printers: printer.getPrinters()});
});

router.get('/printjob', function(req, res) {
	db.serialize(function() {
		db.all("SELECT * FROM print_job ORDER BY id DESC", function(err, rows) {
			res.render('printjob', {jobs:rows});
		});
	})
});

router.post('/submit', [bodyParser.json()], function(req, res) {
	var data = req.body;
  console.log('body', data);
	// db.serialize(function() {
	db.run("INSERT INTO print_job (uuid, report, param, file, format, printer, status, num_copy) "
		+ "VALUES($uuid, $report, $param, $file, $format, $printer, $status, $numCopy)", {
		$uuid: data.uuid,
		$report: data.report,
		$param: JSON.stringify(data.param),
		$file: '',
		$format: data.format,
		$printer: data.printer,
		$status: 'PENDING',
		$numCopy: data.numCopy,
	});
	//});

  res.send({status:true});
});

jobWatcher.run();


module.exports = router;
