/**
 *  ---------
 * |.##> <##.|  Open Smart Card Development Platform (www.openscdp.org)
 * |#       #|
 * |#       #|  Copyright (c) 2020 CardContact Systems GmbH
 * |'##> <##'|  Schuelerweg 38, 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 Base model for enrollable subjects (Person / System)
 * to determine the corresponding trust center if available
 */

var SubjectModel	= require('pki-as-a-service/service/SubjectModel').SubjectModel;
var TrustCenter		= require('pki-as-a-service/subjects/TrustCenter').TrustCenter;


/**
 * Data model for System Subject
 *
 *
 * @constructor
 */
function EnrolledSubject(service, bo) {
	SubjectModel.call(this, service, bo);
}

EnrolledSubject.prototype = Object.create(SubjectModel.prototype);
EnrolledSubject.constructor = EnrolledSubject;

exports.EnrolledSubject = EnrolledSubject;



EnrolledSubject.prototype.getTrustCenterId = function() {
	if (!this.bo.serviceRequestId) {
		GPSystem.log(GPSystem.DEBUG, module.id, "No serviceRequestId set in subject " + this.bo.id);
		return;
	}

	var srDAO = this.service.daof.getServiceRequestDAO();
	var sr = srDAO.getServiceRequestById(this.bo.serviceRequestId);

	if (sr.process != "EnrollPersonServiceRequest" &&
		sr.process != "EnrollSystemServiceRequest") {
		GPSystem.log(GPSystem.DEBUG, module.id, "Subject " + this.bo.id + " was not enrolled by a trust center");
		return;
	}

	return sr.recipientId;
}



EnrolledSubject.prototype.getTrustCenter = function() {
	var id = this.getTrustCenterId();
	if (!id) {
		return;
	}

	var subject = this.service.getSubject(id);
	if (!(subject instanceof TrustCenter)) {
		GPSystem.log(GPSystem.ERROR, module.id, "Unexpected subject type " + subject);
		throw new GPError(module.id, GPError.INVALID_TYPE, 0, "Unexpected subject type " + subject);
	}

	return subject;
}
