/**
 *  ---------
 * |.##> <##.|  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 publishing CRLs
 */



/**
 * Service publishing CRLs
 */
function CRLPublisher(daof) {
	this.name = "CRLPublisher";

	this.daof = daof;
	this.signerDAO = this.daof.getSignerDAO();
	this.holderDAO = this.daof.getHolderDAO();
	this.subjectDAO = this.daof.getSubjectDAO();

	this.crls = [];
}

exports.CRLPublisher = CRLPublisher;



/**
 * Add crl to internal list of CRLs
 */
// CRLPublisher.prototype.publishCRL = function(name, crl) {
// 	this.crls[name] = crl;
// }



/**
 * Get filename
 *
 * @param {Holder} holder the holder
 * @param {Subject} subject the subject
 * @param {Number} crlNumber the CRL number
 */
CRLPublisher.getFilename= function(holder, subject, crlNumber) {
	var filename = subject.name + "-" + holder.name;

	if (crlNumber) {
		filename += "-" + crlNumber;
	}

	filename += ".crl";

	return filename;
}



/**
 * Dispatch all GET inquiries
 *
 * @param {HttpRequest} req the request object
 * @param {HttpResponse} req the response object
 */
CRLPublisher.prototype.handleRequest = function(req, res) {
	var url = req.pathInfo.substr(1).split("/");

	var id = Number(url[1]);
	var signer = this.signerDAO.getSignerByID(id);
	if (signer) {
		var c = signer.getContent();
		if (c.crl) {
			var holder = this.holderDAO.getHolderById(signer.holderId);
			var subject = this.subjectDAO.getSubject(holder.subjectId);
			var filename = CRLPublisher.getFilename(holder, subject);
			GPSystem.log(GPSystem.DEBUG, module.id, "Filename = " + filename);

			var crl = new ByteString(c.crl, HEX);
			res.setContentType("application/pkix-crl");
			res.setContentLength(crl.length);
			res.nativeResponse.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
			res.write(crl);
			return
		}
	}

	GPSystem.log(GPSystem.ERROR, module.id, "No CRL for ID " + id + " found");
	res.setStatus(HttpResponse.SC_NOT_FOUND);
	return;
}
