/**
 *  ---------
 * |.##> <##.|  Open Smart Card Development Platform (www.openscdp.org)
 * |#       #|
 * |#       #|  Copyright (c) 1999-2013 CardContact Software & System Consulting
 * |'##> <##'|  Andreas Schwier, 32429 Minden, Germany (www.cardcontact.de)
 *  ---------
 *
 *  This file is part of OpenSCDP.
 *
 *  OpenSCDP is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License version 2 as
 *  published by the Free Software Foundation.
 *
 *  OpenSCDP is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with OpenSCDP; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @fileoverview Simple ScriptingServer that sends APDUs to a remote SmartCard-HSM
 */


var serverURL = "http://localhost:8080";



/**
 * Process an incoming HTTP request
 *
 * @param {HTTPRequest} req the request
 * @param {HTTPResponse} res the response
 */
function handleRequest(req, res) {
	GPSystem.trace("Request received.");
	var session = req.getSession();

	var sessionId = req.getSession().id;
	var rndstr = Math.floor(Math.random() * 10000000).toString();

	var url = "http://localhost:27001/" + rndstr + ".png?url=" + serverURL + "/rt/testappl&sessionId=" + sessionId;

	var page =
		<html>
			<head>
				<title>Scripting Server - Hello World</title>
			</head>
			<body>
			</body>
		</html>

	if (req.queryString) {
		delete session.state;
		res.setStatus(HttpResponse.SC_SEE_OTHER);
		res.addHeader("Location", req.servletPath);
		return;
	}

	if (typeof(session.state) == "undefined") {
		page.body = <body>
						<p>Session id {sessionId}</p>
						<p>Please start local client by double-click on ocf-cc.jar or using the following command line</p>
						<pre>java -jar ocf-cc.jar</pre>
						<p>and press <a href="">continue</a></p>
					</body>
		session.state = {};
	} else {
		if (typeof(session.state.challenge) == "undefined") {
			page.body = <body>
						<p>Updating card <img onload="window.location.reload()" src={url} width="16" height="16"/></p>
						<p>Please wait for the green tick to appear. The page will be reloaded automatically if JavaScript is enabled.</p>
						<p>If JavaScript is disabled, then press <a href="">continue</a> after the green tick is shown.</p>
						<p>Select <a href="?reset">reset</a> to start over.</p>
					</body>
		} else {
			page.body = <body>
							<p>Read challenge</p>
							<pre>{session.state.challenge.toString(HEX)}</pre>
							<p>from card. <a href="?reset">Restart</a></p>
						</body>
		}
	}

	res.print(page.toXMLString());
}



/**
 * Perform a card update
 *
 * @param {HttpSession} sessionid The session id to be used as card reader name
 * @param {String} pathInfo The additional path elements addressing the application
 *
 */
function performCardUpdate(session, pathInfo) {
	GPSystem.trace("Request received for session " + session.id + " at " + pathInfo);
	if (session.cardTerminal) {
		var card = new Card(session.cardTerminal);
	} else {
		var card = new Card(session.id);
	}

	try	{
		var atr = card.reset(Card.RESET_COLD);
		print(atr);

		ctr = ctr = Packages.opencard.core.terminal.CardTerminalRegistry.getRegistry();
		ct = ctr.cardTerminalForName(session.id);
		ct.sendNotification(0, "Test");

		card.sendApdu(0x00, 0x20, 0x00, 0x81);
		if (card.SW != 0x9000) {
			var aid = new ByteString("E82B0601040181C31F0201", HEX);
			var rsp = card.sendApdu(0x00, 0xA4, 0x04, 0x04, aid, 0, [0x9000]);

			card.sendApdu(0x00, 0x20, 0x00, 0x81, new ByteString("648219", ASCII));
		}

		for (var i = 0; i <= 1; i++) {
			print(i);
			var rsp = card.sendApdu(0x00, 0x84, 0x00, 0x00, 0x45, [0x9000]);
		}
		if (typeof(session.state) != "undefined") {
			session.state.challenge = rsp;
		}
	}
	finally {
		card.close();
	}
}


GPSystem.trace("Script updatecard.js completed...");
