const chokidar = require('chokidar');
const paths = require('path');
const mv = require('mv');
const fs = require('fs');
const moment = require('moment');
const nrc = require('node-run-cmd');
const htmlPdf = require('html-pdf-chrome');
const options = { 
	port: 42020,
	printOptions:{
		marginBottom: 0,
		marginLeft: 0,
		marginTop: 0,
		marginRight: 0
	}
};
var now = moment().format('YYYYMMDDHHmmss');

chokidar.watch('process_pdf/' , { ignoreInitial: false, awaitWriteFinish: true, depth:0 }).on('add', (path) => {
	if(paths.extname(path)=='') {
		console.log('raw file processed '+path);
		nrc.run('php main2.php '+path).then( function(){
			mv(path, "done_pdf/"+paths.basename(path) , function (err) {
				if (err) throw err;
			});
		});
	}
	else if(paths.extname(path)=='.html') {
		url = "file://C:/inetpub/wwwroot/spooler_db/process_pdf/"+paths.basename(path);
		console.log('generating pdf '+url);
		htmlPdf.create(url, options).then((pdf) => pdf.toFile("C:\\inetpub\\wwwroot\\spooler_db\\process_pdf\\"+paths.basename(path,'.html')+".pdf")).then( function(err) {
			mv(path, "done_pdf/"+paths.basename(path) , function (err) {
				if (err) throw err;
			})	
		});
		
	}
});