/**
 *  ---------
 * |.##> <##.|  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 Configure SmartCard-HSM Personalization Server
 */



function CommonUI(service) {
	if (service) {
		this.service = service;
		this.bookmarks = [];
	}
}



/**
 * Parse operations string into object containing parameter and values
 *
 * <p>An operations string may contain multiple entries separated by an ampersand.</p>
 * <p>Entries may have a value assigned using the parameter=value notation.</p>
 * <p>Valid operations strings are "link", "link=all", "filer=true&start=0"</p>
 *
 * @param {String} op the operations string
 * @returns an object with properties matching entries.
 * @type Object
 */
CommonUI.parseQueryString = function(op) {
	var result = {};

	var elems = op.split("&");
	for (var i = 0; i < elems.length; i++) {
		var s = elems[i];
		var ofs = s.indexOf("=");
		if (ofs >= 0) {
			var p = s.substring(ofs + 1);
			s = s.substring(0, ofs);
			result[s] = p;
		} else {
			result[s] = true;
		}
	}
	return result;
}



CommonUI.prototype.homeURL = function(url) {
	var prefix = "";
	for (var i = 1; i < url.length; i++) {
		prefix += "../";
	}
	return prefix + url[0];
}



CommonUI.prototype.redirectToMainPage = function(req, res, url) {
	res.setStatus(HttpResponse.SC_SEE_OTHER);
	res.addHeader("Location", this.homeURL(url));
}



/**
 * Generate a HTML template
 *
 * @param {String[]} url the array of URL elements
 * @returns the HTML page template
 * @type XML
 */
CommonUI.prototype.generateTemplate = function(url) {
	default xml namespace = "http://www.w3.org/1999/xhtml";

	var prefix = "";
	for (var i = 1; i < url.length; i++) {
		prefix += "../";
	}

	var pagetemplate =
		<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en" >
			<head>
				<title>{this.service.type + " " + this.service.name}</title>
				<link rel="stylesheet" type="text/css" href={prefix + "../css/style.css"}/>
			</head>
			<body>
				<div align="left">
					<a href="http://www.cardcontact.de"><img src={prefix + "../images/banner.jpg"} width="750" height="80" border="0"/></a>
				</div>
				<div id="navigator">
					<p><b>Perso</b></p>
					<a href={this.homeURL(url)}>Home</a><br/>
					<a href="/">Server</a><br/>
					<br/>
					<div id="bookmarks"/>
				</div>
				<div id="main">
					<div id="content"/>
					<p class="copyright">(c) Copyright 2003 - 2016 <a href="http://www.cardcontact.de">CardContact Systems GmbH</a>, Minden, Germany</p>
				</div>
			</body>
		</html>
	return pagetemplate;
}



/**
 * Send page after embedding in the HTML template
 *
 * @param {HttpRequest} req the request object
 * @param {HttpResponse} req the response object
 * @param {String[]} url the array of URL elements
 * @param {XML} page the page contents
 */
CommonUI.prototype.sendPage = function(req, res, url, page) {
	default xml namespace = "http://www.w3.org/1999/xhtml";

	var t = this.generateTemplate(url);
	var c = t..div.(@id == "content");
	c.div = page;

/*
	var bml = <div/>;
	for (var i = 0; i < this.bookmarks.length; i++) {
		var bm = this.bookmarks[i];
		bml.appendChild(<a href={bm.url}>{bm.name}</a>);
		bml.appendChild(<br/>);
	}
	var c = t..div.(@id == "bookmarks");
	c.div = bml;
*/

	res.setContentType("application/xhtml+xml");
	res.print('<?xml version="1.0" encoding="UTF-8" standalone="no"?>');
	res.print('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n');
	res.print(t.toXMLString());
}



function PersoServiceGUI(service) {
	this.service = service;
	CommonUI.call(this, service);
	this.currentJob = this.service.getJobs()[0];
}

PersoServiceGUI.prototype = new CommonUI();
PersoServiceGUI.constructor = PersoServiceGUI;



PersoServiceGUI.prototype.serveMainPage = function(req, res, url) {
	default xml namespace = "http://www.w3.org/1999/xhtml";
	var page =
		<div>
			<h1>Personalization Server</h1>
			<form action="" method="get">
				Select Job
				<input name="op" type="hidden" value="changejob"/>
				<select name="job" size="1" onchange="this.form.submit()">
				</select>
				<button type="submit">Refresh</button>
			</form>
			<div id="overview"/>
		</div>

	var l = page.form.select.(@name=="job");
	var joblist = this.service.getJobs();
	var job = null;

	for each (var j in joblist) {
		if (this.currentJob.id == j.id) {
			l.option += <option value={j.id} selected="selected">{j.description}</option>
			job = j;
		} else {
			l.option += <option value={j.id}>{j.description}</option>
		}
	}

	if (job) {
		var t = <table class="content"/>;
		t.colgroup += <colgroup><col width="120"/><col/></colgroup>
		t.tr += <tr><td>Id</td><td>{job.id}</td></tr>;
		t.tr += <tr><td>Description</td><td>{job.description}</td></tr>;
		t.tr += <tr><td>Good cards</td><td>{job.handler.good}</td></tr>;
		t.tr += <tr><td>Bad cards</td><td>{job.handler.bad}</td></tr>;
	} else {
		var t = <p>Please configure jobs in jobs/jobs.js</p>
	}

	var div = page.div.(@id == "overview");
	div.h2 = "Overview";
	div.appendChild(t);

	this.sendPage(req, res, url, page);
}



PersoServiceGUI.prototype.handleJoblistXML = function(req, res) {

	var joblist = this.service.getJobs();
	var t = <jobs>
	</jobs>

	for each (var j in joblist) {
		t.job += <job description={j.description} id={j.id} />
	}

	res.setContentType("text/xml");
	res.print(t.toXMLString());
}



PersoServiceGUI.prototype.handleRequest = function(req, res) {
	// pathInfo always starts with an "/"
	var url = req.pathInfo.substr(1).split("/");

	// Handle details view
	if (url.length > 1) {
		var detailsType = url[1];
		GPSystem.trace("Handle details for :" + detailsType);
		switch(detailsType) {
		case "joblistxml":
			this.handleJoblistXML(req, res, url);
			break;
		default:
			res.setStatus(HttpResponse.SC_NOT_FOUND);
			return;
		}
	} else {
		// Handle operations
		if (req.queryString) {
			// Handle operations
			var operation = CommonUI.parseQueryString(req.queryString);
			switch(operation.op) {
			case "changejob":
				this.currentJob = this.service.getJob(operation.job);
				break;
			}
			this.redirectToMainPage(req, res, url);
		} else {
			this.serveMainPage(req, res, url);
		}
	}
}
