var express     = require('express');
var router      = express.Router();
var bodyParser  = require('body-parser');

var easyusb 	= require('easyusb');

router.post('/ttp244', bodyParser.json(), function(req, res) {
	var data = req.body;
	var i = 0;
	var send_limit = 20;
	var cls = true, wait = true;
	var setting = 'SIZE 99 mm,18 mm\r\nGAP 1 mm,0 mm\r\nDIRECTION 1\r\n',  text = setting;

	var device = easyusb([[0x1203, 0x133]]);

	var GenerateBarcode = function(){
		text = setting;
		for (var j = 0; j < send_limit && i+j < data.length; j++) { 

			var X = (j % 2 == 0) ? { text:432, barcode:468 } : { text:32, barcode:68 };
			if(cls) text += 'CLS\r\n';
			cls = false;
			text += 'TEXT '+X.text+',100,"ROMAN.TTF",270,8,8, "SIAMCHAI"\r\n';
			text += 'BARCODE '+X.barcode+',18,"128",60,2,0,2,2,"' + data[i+j] + '"\r\n';
			// PRINT AND NEXT BARCODE
			if(j % 2 != 0 || send_limit-1 == j || data.length-1 == i+j) { text += 'PRINT 1\r\n'; cls = true; }
		}

		i = i+j;
		device.write(text, function(err) {
			if(err) console.log('write',err);
			if(i < data.length) {
				setTimeout(function() { process.nextTick(GenerateBarcode); }, 4000);
			} else {
				device.close();
				res.send({ status:true });
			}
		});
	}

	try
	{
		GenerateBarcode();
	} catch(e) {
		res.send({ status:false });
	}

});

module.exports = router;