/**
 *  ---------
 * |.##> <##.|  Open Smart Card Development Platform (www.openscdp.org)
 * |#       #|
 * |#       #|  Copyright (c) 1999-2016 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 Card related actions performed in the UI
 */



var CommonUI			= require('scsh/srv-cc1/CommonUI').CommonUI;
var CardAction			= require('scsh/srv-cc1/CardAction').CardAction;



function PKIAPICardActionWizard(ui, apiConnector, srID, data, rtURL, redirectUrl) {
	CardAction.call(this, ui);
	this.apiConnector = apiConnector;
	this.srID = srID;
	this.data = data;
	this.rtURL = rtURL;
	this.redirectUrl = redirectUrl;
	this.requestPIN = 1;
	this.allowRestart = false;
	GPSystem.log(GPSystem.DEBUG, module.id, "new PKIAPICardActionWizard(" + srID + "," + redirectUrl + ")");

}


PKIAPICardActionWizard.prototype = Object.create(CardAction.prototype);
PKIAPICardActionWizard.constructor = PKIAPICardActionWizard;

exports.PKIAPICardActionWizard = PKIAPICardActionWizard;



/**
 * Sets an optional completion handler
 */
PKIAPICardActionWizard.prototype.setCompletionHandler = function(callback) {
	this.callback = callback;
}



/**
 * Check the status of the card action using the action status query
 *
 * @param {HttpRequest} req the request object
 * @param {HttpResponse} req the response object
 */
PKIAPICardActionWizard.prototype.getPage = function(req, res, url) {
	GPSystem.log(GPSystem.DEBUG, module.id, "getPage() : CardAction state: " + this.state);

	if (this.state != CardAction.NEW && this.state != CardAction.SUCCESS) {
		var rsp = this.apiConnector.getCardActionStatus(this.srID);
		if (rsp.message == "msg.completed") {
			this.state = CardAction.SUCCESS;
			this.pending = false;
			if (typeof(this.callback) != "undefined") {
				GPSystem.log(GPSystem.DEBUG, module.id, "Execute completion handler");
				this.callback();
			}
		} else if (rsp.message == "msg.pending") {
			this.state = CardAction.NOCLIENT;
		} else if (rsp.message == "msg.failed") {
			this.state = CardAction.ERROR;
			this.pending = false;
			this.reportError(rsp.detail);
		} else if (rsp.message == "msg.running") {
			this.pending = true;
		}
	}

	return CardAction.prototype.getPage.call(this, req, res, url);
}



/**
 * Get the activation link for the redirect to the local client
 *
 * @param {HttpRequest} req the request object
 * @param {HttpResponse} req the response object
 */
PKIAPICardActionWizard.prototype.getActivationLink = function(req, res, requestPin) {
	default xml namespace = "http://www.w3.org/1999/xhtml";

	GPSystem.log(GPSystem.DEBUG, module.id, "getActivationLink");

	var rndstr = Math.floor(Math.random() * 10000000).toString();

//	print("### " + this.sessionId);
	if (typeof(this.sessionId) == "undefined") {
		try	{
			var rsp = this.apiConnector.postAction(this.srID, this.data);
			if (rsp.message != "msg.pending") {
				this.reportError("API Error : " + rsp.detail);
				return null;
			}
			this.sessionId = rsp.sessionId;
		}
		catch(e if e instanceof GPError) {
			GPSystem.log(GPSystem.ERROR, module.id, e);
			GPSystem.log(GPSystem.ERROR, module.id, e.stack);
			this.reportError("Could not connect to API: " + e.message);
			return null;
		}
	}

	var url = "http://127.0.0.1:27001/" + rndstr + ".png?url=" + this.rtURL + "&sessionId=" + this.sessionId;

	if (requestPin >= 0) {
		 url += "&pinrequired=" + requestPin;
	}
	if (this.aid) {
		 url += "&aid=" + this.aid;
	}

	GPSystem.log(GPSystem.DEBUG, module.id, "url = " + url);

	return <img onload="window.location.reload()" onerror="alert('Could not connect to local client. Is the client running ?');window.location.reload()" src={url} width="16" height="16"/>;
}



PKIAPICardActionWizard.prototype.handleRequest = function(req, res) {
	default xml namespace = "http://www.w3.org/1999/xhtml";
	GPSystem.log(GPSystem.DEBUG, module.id, "handleRequest");

	var page = this.getPage(req, res, req.url);
	if (page) {
		var t = this.ui.generateTemplate(req.url);
		var c = t..div.(@id == "content");
		c.div = page;
		this.ui.sendPage(req, res, req.url, t);
	} else {
		GPSystem.log(GPSystem.DEBUG, module.id, "redirect to " + this.redirectUrl);
		this.ui.redirectTo(req, res, req.url, this.redirectUrl);
	}
}
