/**
 *  ---------
 * |.##> <##.|  Open Smart Card Development Platform (www.openscdp.org)
 * |#       #|
 * |#       #|  Copyright (c) 2017 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 RoleController
 */

function RoleController(ui) {
	this.ui = ui;
	this.service = ui.service;
}

exports.RoleController = RoleController;



RoleController.prototype.getRole = function(req, res) {
	var id = parseInt(req.url[2]);

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

	var dao = this.service.daof.getRoleDAO();
	var bo = dao.getRoleById(id);
	if (!bo) {
		throw new GPError(module.id, GPError.INVALID_DATA, 0, "No role found with id " + id);
	}

	return bo;
}



RoleController.prototype.getView = function(req, res, role) {
	default xml namespace = "http://www.w3.org/1999/xhtml";

	var page =	<div>
				<h1>{ role.name }</h1>
			</div>;

	var dao = this.service.daof.getRoleDAO();
	var subjects = dao.getAssignedSubject(role.id);
	var url = this.ui.homeURL(req.url) + "/subject/";
	var ul = <ul/>;
	for (var i = 0; i < subjects.length; i++) {
		ul.li += <li><a href={ url + subjects[i].id }>{ subjects[i].id }</a></li>
	}
	page.appendChild( <h2>Assigned Subjects</h2> );
	page.appendChild(ul);

	return page;
}



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

	if (req.url.length < 3) {
		throw new GPError(module.id, GPError.INVALID_DATA, 0, "Invalid URL");
	}


	var role = this.getRole(req, res);

// 	if (req.method == "POST") {
// 		if (!sr.canRead(this.ui.session.user)) {
// 			res.setStatus(HttpResponse.SC_FORBIDDEN);
// 			return;
// 		}
// 	} else {
// 		if (!sr.canRead(this.ui.session.user)) {
// 			this.ui.serveNotAuthorizedPage(req, res, req.url);
// 			return;
// 		}
// 	}
	var page = this.getView(req, res, role);
	var t = this.ui.generateTemplate(req.url);
	var c = t..div.(@id == "content");
	c.div = page;

	this.ui.sendPage(req, res, req.url, t);
}
