/**
 *  ---------
 * |.##> <##.|  Open Smart Card Development Platform (www.openscdp.org)
 * |#       #|
 * |#       #|  Copyright (c) 1999-2018 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 Enrollment over Secure Transport (EST) certificate requests
 */

var SubjectDAO = require('scsh/pki-db/db/SubjectDAO').SubjectDAO;
var I18N = require('scsh/srv-cc1/I18N').I18N;
var CertificateRequestController = require('x509ca/processes/CertificateRequestController').CertificateRequestController;



I18N.addResources([
	{ lang: "EN", keys: {
		"msg.pkcs10.req": "PKCS#10 Request",
		"msg.cr.keyType": "Key Type",
		"msg.cr.keySize": "Key Size",
		"msg.cr.curve": "Curve Name",
		"msg.cr.issuer": "Issuing CA",

		"action.pkcs10.upload": "Upload",
		"action.pkcs10.accept": "Accept Certificate"
	}}
]);



function ESTRequestController() {
	GPSystem.log(GPSystem.DEBUG, module.id, "new ESTRequestController()");
	CertificateRequestController.call(this);
}

ESTRequestController.prototype = Object.create(CertificateRequestController.prototype);
ESTRequestController.constructor = ESTRequestController;

exports.ESTRequestController = ESTRequestController;



ESTRequestController.prototype.createRequest = function(srct, parameter) {

	var holderId = parseInt(parameter.ca);
	GPSystem.log(GPSystem.DEBUG, module.id, "Selected CA:" + holderId);

	// Obtain initialized subject object
	var holderDAO = srct.ui.service.daof.getHolderDAO();
	var ca = holderDAO.getHolderById(holderId);

	if (ca == null) {
		throw new GPError(module.id, GPError.INVALID_DATA, 0, "Can't find CA holder");
	}

	var trustCenter = srct.service.getSubject(ca.subjectId);

	if (trustCenter == null) {
		throw new GPError(module.id, GPError.INVALID_DATA, 0, "Can't find trust center");
	}

	var srDAO = srct.service.daof.getServiceRequestDAO();

	var t = {
		process: "ESTServiceRequest",
		title: srct.i18n("msg.cr.title"),
		originatorId: srct.ui.session.user.id,
		recipientId: trustCenter.bo.id,
		state: "New request",
		content: {
			issuer: holderId
		}
	};

	if (!trustCenter.checkServiceRequestCreation(srct.ui.session.user, t)) {
		return undefined;
	}

	if (trustCenter.canRead(srct.ui.session.user)) {
		var bo = srDAO.newServiceRequest(t);
	}
	return bo;
}



ESTRequestController.prototype.postCreateAction = function(req, res, srct, action) {
	var bo = this.createRequest(srct, req.parameters);

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



ESTRequestController.prototype.postProcessAction = function(req, res, srct, sr, action) {

	switch(action) {
	case "action.save":
	case "action.pkcs10.upload":
	case "action.submit":
		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;
	default:
			return CertificateRequestController.prototype.postProcessAction.call(this, req, res, srct, sr, action);
	}

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

	return false;
}



ESTRequestController.prototype.getCreateView = function(req, res, srct) {
	default xml namespace = "http://www.w3.org/1999/xhtml";

	var div =	<div>
				<h1>Request a Certificate</h1>
				<p>This service will request a new certificate from one of the registered
				   certification authorities.</p>
			</div>

	var form =
		<form class="pure-form" action="" method="post" enctype="multipart/form-data">
			<p>Please select a certification authority from which you would like to receive a certificate.</p>
			<select name="ca"/>
			<button class="pure-button" type="submit" name="action" value="create">Start Request</button>
		</form>

	var subjectDAO = srct.ui.service.daof.getSubjectDAO();
	var l = form.select;
	var trustCenters = subjectDAO.listSubjectsByType(SubjectDAO.TYPE_TRUST_CENTER);
	for each (var subject in trustCenters) {
		var trustCenter = srct.service.getSubject(subject.id);
		if (trustCenter.canRead(srct.ui.session.user)) {
			var optgroup = <optgroup label={ trustCenter.getName() } />;
			var caList = trustCenter.getCAList();
			for each (var ca in caList) {
				optgroup.appendChild(<option value={ca.id}>{ca.getReadablePath()}</option>);
			}
			if (caList.length > 0) {
				l[0].appendChild(optgroup);
			}
		}
	}

	if (l.optgroup.length() > 0) {
		div.appendChild(<p>The service request consists of the following steps:</p>);
		div.appendChild(
			<ol>
				<li>You select from which certification authority you would like to receive a certificate</li>
				<li>You upload the PKCS#10 Certificate Request file</li>
				<li>The request will be forwarded to a registration officer of the CA</li>
				<li>The registration officer either approves or rejects your request</li>
				<li>If the request is approved, then it is forwarded to the certification officer of the CA</li>
				<li>The certification officer will issue the certificate</li>
				<li>The certificate is available for download</li>
			</ol>);
		div.appendChild(form);
	} else {
		div.appendChild(<p>There is no accessible certification authority. This is either the case if there are no operational certification authorities or you are not authorized to access a private certification authority.</p>);
	}
	return div;
}



ESTRequestController.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));

	if (sr.hasCertificates() > 0) {
		div.appendChild( <br/> );
		div.appendChild( <h2>Certificates</h2> );
		div.appendChild(srct.renderCertificateList(req, res, sr));
	}

	return div;
}
