/**
 *  ---------
 * |.##> <##.|  SmartCard-HSM Support Scripts
 * |#       #|
 * |#       #|  Copyright (c) 2011-2012 CardContact Software & System Consulting
 * |'##> <##'|  Andreas Schwier, 32429 Minden, Germany (www.cardcontact.de)
 *  ---------
 *
 * Consult your license package for usage terms and conditions.
 *
 * @fileoverview Personalization Client
 */



function PersoClient(url) {
	this.url = url;
	this.term = new AccessTerminal();
	this.term.green();
}



PersoClient.prototype.selectJob = function() {
	var con = new URLConnection(this.url + "/se/ps/joblistxml");
	var lst = new XML(con.get());
	var sellst = [];
	for each (var job in lst.job) {
		sellst.push(job.@id + ": " + job.@description);
	}
	var sel = Dialog.prompt("Please select job", "", sellst);
	if (sel == null) {
		throw new Error("User abort...");
	}

	this.jobid = sel.split(":")[0];
}



PersoClient.prototype.passed = function(msg) {
	print("Personalization complete: " + msg);
	this.term.green();
}



PersoClient.prototype.failed = function(msg) {
	print("Personalization failed with " + msg);

	GPSystem.wait(200);
	this.term.red();
	GPSystem.wait(200);
	this.term.off();
	GPSystem.wait(200);
	this.term.red();
}



PersoClient.prototype.cardInserted = function(readername) {
	if (_scsh3.reader && _scsh3.reader.length && (readername != _scsh3.reader)) {
		return;
	}

	this.term.off();
	var card = new Card(readername);
	card.remoteUpdate(this.url + "/rt/ps/" + this.jobid);

	if (card.remoteMessageId != 0) {
		this.failed(card.remoteMessage);
	} else {
		this.testCard(card);
		this.passed(card.remoteMessage);
	}

	card.close();
}



PersoClient.prototype.cardRemoved = function(readername) {
	if (_scsh3.reader && _scsh3.reader.length && (readername != _scsh3.reader)) {
		return;
	}

	this.term.green();
	GPSystem.wait(200);
	this.term.off();
	GPSystem.wait(200);
	this.term.green();
}


PersoClient.prototype.testCard = function(card) {
	card.reset(Card.RESET_COLD);
	print("Test OK");
}



var url = "http://localhost:8080";
url = Dialog.prompt("Please enter personalization server URL: ", url);
if (url == null) {
	print("Aborting...");
} else {
	// Create perso manager
	var pc = new PersoClient(url);
	pc.selectJob();
	Card.setCardEventListener(pc);

	print("Personalization system ready. Please insert card to be personalized.");
}
