/**
 *  ---------
 * |.##> <##.|  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 Service request controller for CertificateServiceRequest
 */

var InitializationWizard = require('pki-as-a-service/ui/InitializationWizard').InitializationWizard;
var CardActionWizard = require('pki-as-a-service/ui/CardActionWizard').CardActionWizard;
var ServiceRequestModel = require('pki-as-a-service/service/ServiceRequestModel').ServiceRequestModel;
var CommonUI = require('scsh/srv-cc1/CommonUI').CommonUI;
var I18N = require('scsh/srv-cc1/I18N').I18N;
var TrustCenter = require('pki-as-a-service/subjects/TrustCenter').TrustCenter;



I18N.addResources([
	{ lang: "EN", keys: {
		"msg.it.title": "Issue Token",
		"msg.it.token": "Token",
		"msg.it.id": "ID",
		"msg.it.status": "Status",
		"msg.it.issuer": "Issuer",
		"msg.it.ca": "CA",
		"msg.it.init": "Token Configuration",
		"msg.it.derivationKeyLabel": "SO-PIN Derivation Key",
		"msg.it.rrcMode": "Resetting PIN with SO-PIN allowed",
		"msg.it.withoutRRC": "Not Allowed",
		"msg.it.withRRC": "Changing and Unblocking of the PIN Allowed",
		"msg.it.resetOnly": "Only Unblocking of the PIN Allowed",
		"msg.it.transportMode": "Transport PIN enabled",
		"msg.it.pin": "PIN",
		"msg.it.noOfKeyDomains": "Number of Key Domains",
		"msg.it.assignedTo": "Token is currently assigned to {0}. Please be carefull when you deregister.",

		"action.selectToken": "Identify Token",
		"action.selectToken.tooltip": "Identify the token inserted into your client and determine it's status in the portal",
		"action.registerToken": "Register Token",
		"action.registerToken.tooltip": "Register the identified token with this subject",
		"action.deregisterToken": "Deregister Token",
		"action.deregisterToken.tooltip": "Withdraw the token from the subject it is currently assigned to (Warning: Use with care !)",
		"action.initialize": "Initialize Token",
		"action.initialize.tooltip": "Initialize the identified token with selected initialisation parameter",
		"action.reqCert": "Request Certificate",
		"action.reqCert.tooltip": "Request a certificate from the CA associated with this request"
	}}
]);



function IssueTokenRequestController() {
	GPSystem.log(GPSystem.DEBUG, module.id, "new IssueTokenRequestController()");
}

exports.IssueTokenRequestController = IssueTokenRequestController;



IssueTokenRequestController.prototype.getSubject = function(req, res, srct) {
	var parameter = CommonUI.parseQueryString(req.queryString);
	var id = Number(parameter.for);

	if (isNaN(id) || id == 0) {
		throw new GPError(module.id, GPError.INVALID_DATA, 0, "Argument id not valid in URL");
	}

	var subject = srct.service.getSubject(id);

	return subject;
}



/**
 * Handle POST request to create service request and initiate a GET after POST redirect to
 * the newly created service request.
 *
 * @param {HttpRequest} req the request object
 * @param {HttpResponse} res the response object
 * @param {ServiceRequestController} srct the service request controller in which this controller is embedded.
 * @param {String} action from the POST parameter
 * @type boolean
 * @return true if processing completed, false if it failed
 */
IssueTokenRequestController.prototype.postCreateAction = function(req, res, srct, action, subject) {

	var trustCenter = subject.getTrustCenter();
	if (!trustCenter.canEnroll(srct.ui.session.user)) {
		return false;
	}

	var nameOrEmail = subject.bo.name ? subject.bo.name : subject.bo.email;
	var t = {
		process: "IssueTokenServiceRequest",
		title: srct.i18n("msg.it.title"),
		details: nameOrEmail,
		recipientId: trustCenter.getId(),
		lifecycle: ServiceRequestModel.LIFECYCLE_EDIT,
		content: {
			subjectId: subject.getId()
		}
	};

	var vo = srct.createServiceRequest(t);

	srct.ui.redirectTo(req, res, req.url, "/sr/" + vo.id);
	return true;
}



/**
 * Handle POST request to update service request.
 *
 * @param {HttpRequest} req the request object
 * @param {HttpResponse} res the response object
 * @param {ServiceRequestController} srct the service request controller in which this controller is embedded.
 * @param {ServiceRequestModel} sr the service request model, typically a derived class
 * @param {String} action from the POST parameter
 * @type boolean
 * @return true if processing results in a new URL or an error page was generated, false if GET after POST in calling
 * service request controller is desired.
 */
IssueTokenRequestController.prototype.postProcessAction = function(req, res, srct, sr, action) {
	GPSystem.log(GPSystem.DEBUG, module.id, "handleAction: " + action);

	switch(action) {
	case "action.create":
	case "action.save":
		if (!sr.setFields(srct.ui.session.user, req.parameters)) {
			var page = srct.getProcessView(req, res, sr);
			srct.ui.sendPage(req, res, req.url, page);
			return true;
		}
		break;
	case "action.registerToken":
		break;
	case "action.deregisterToken":
		break;
	case "action.initialize":
		srct.ui.wizard = new InitializationWizard(srct.ui, sr, "/" + req.url[1] + "/" + req.url[2]);
		srct.ui.wizard.requestPIN = -1;
		srct.ui.redirectTo(req, res, req.url, "/wizard");
		return true;
	case "action.selectToken":
		srct.ui.wizard = new CardActionWizard(srct.ui, sr, "/" + req.url[1] + "/" + req.url[2]);
		srct.ui.wizard.requestPIN = -1;
		srct.ui.redirectTo(req, res, req.url, "/wizard");
		return true;
	}

	sr.perform(srct.ui.session.user, action);

	return false;
}



/**
 * Handle GET request to show page with information about creating this service request.
 *
 * @param {HttpRequest} req the request object
 * @param {HttpResponse} res the response object
 * @param {ServiceRequestController} srct the service request controller in which this controller is embedded.
 * @type XML
 * @return The XHTML to be embedded in the service request controller frame.
 */
IssueTokenRequestController.prototype.getCreateView = function(req, res, srct, subject) {
	default xml namespace = "http://www.w3.org/1999/xhtml";

	var subjectLink = srct.ui.homeURL(req.url) + "/subject/" + subject.getId();

	var form =	<div>
				<h1>Issue Token</h1>
			</div>

	var trustCenter = subject.getTrustCenter();

	if (trustCenter == undefined) {
		form.appendChild(
			<p>This user was not enrolled by a trustcenter</p>
		);
		return form;
	}

	GPSystem.log(GPSystem.DEBUG, module.id, "is trustCenter subject? " + (trustCenter instanceof TrustCenter));
	var nameOrEmail = subject.bo.name ? subject.bo.name : subject.bo.email;
	if (trustCenter.canEnroll(srct.ui.session.user)) {
		form.appendChild(
			<p>This service request issues a token for subject <a href={subjectLink}>{nameOrEmail}</a></p>
		);

		form.appendChild(
			<form class="pure-form" action="" method="post" enctype="multipart/form-data">
				<button class="pure-button" type="submit" name="action" value="create">Start Request</button>
			</form>
		);
	} else {
		form.appendChild(
			<p>You are currently not authorized to issue a token for subject <a href={subjectLink}>{nameOrEmail}</a></p>
		)
	}

	return form;
}



/**
 * Handle GET request to show service request details
 *
 * @param {HttpRequest} req the request object
 * @param {HttpResponse} res the response object
 * @param {ServiceRequestController} srct the service request controller in which this controller is embedded.
 * @param {ServiceRequestModel} sr the service request model, typically a derived class
 * @type XML
 * @return The XHTML with service request details to be embedded in the service request controller frame.
 */
IssueTokenRequestController.prototype.getProcessView = function(req, res, srct, sr) {
	default xml namespace = "http://www.w3.org/1999/xhtml";

	var div = <div />;

	div.appendChild(srct.renderForm(req, res, sr));

	return div;
}
