/**
 *  ---------
 * |.##> <##.|  SmartCard-HSM Support Scripts
 * |#       #|
 * |#       #|  Copyright (c) 2011-2024 CardContact Systems GmbH
 * |'##> <##'|  32429 Minden, Germany (www.cardcontact.de)
 *  ---------
 *
 * Consult your license package for usage terms and conditions.
 *
 * @fileoverview Printer control using a shell command
 */

function ShellPrinterControl(param) {
	this.param = param;
	this.runtime = java.lang.Runtime.getRuntime();
}

exports.ShellPrinterControl = ShellPrinterControl;

ShellPrinterControl.type = "printer";



ShellPrinterControl.prototype.configure = function() {
}



/**
 * Execute command and parse first line of output.
 *
 * @param {Object} the command spec
 * @type Boolean
 * @return true if command completed and output matched regex in field ok
 */
ShellPrinterControl.prototype.exec = function(f) {
	GPSystem.trace("Call " + f.cmd);
	var process = this.runtime.exec(f.cmd);

	var reader = new java.io.BufferedReader(new java.io.InputStreamReader(process.getInputStream()));

	var rc = process.waitFor();
	if (rc != 0) {
		GPSystem.trace("Exit code " + rc);
		return false;
	}

	var line = reader.readLine();
	GPSystem.trace(line);
	return line.match(f.ok) != null;
}



/**
 * Move a card in the printer to the reader unit
 */
ShellPrinterControl.prototype.feedCard = function() {
	return this.exec(this.param.feed);
}



/**
 * Eject a good card from the reader unit
 */
ShellPrinterControl.prototype.ejectCard = function() {
	return this.exec(this.param.eject);
}



/**
 * Eject a bad card from the reader unit into the reject outlet
 */
ShellPrinterControl.prototype.rejectCard = function() {
	return this.exec(this.param.reject);
}



ShellPrinterControl.test = function() {
	var param = {
		feed: {
			cmd: [ "evocom", "-pEvolis Quantum2", "Sis;" ],
			ok: /^OK$/
		},
		eject: {
			cmd: [ "evocom", "-pEvolis Quantum2", "Se;" ],
			ok: /^OK$/
		},
		reject: {
			cmd: [ "evocom", "-pEvolis Quantum2", "Ser;" ],
			ok: /^OK$/
		}
	};

	var s = new ShellPrinterControl(param);
	print(s.feedCard());
	print(s.ejectCard());
	print(s.rejectCard());
}
