/**
 *  ---------
 * |.##> <##.|  Open Smart Card Development Platform (www.openscdp.org)
 * |#       #|
 * |#       #|  Copyright (c) 1999-2010 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 A browser for service requests
 */

var CommonUI			= require('scsh/srv-cc1/CommonUI').CommonUI;
var Paginator			= require('pki-as-a-service/ui/Paginator').Paginator;
var MenuModel			= require('pki-as-a-service/ui/MenuModel').MenuModel;
var PureMenuGenerator	= require('pki-as-a-service/ui/PureMenuGenerator').PureMenuGenerator;
var ServiceRequestModel	= require('pki-as-a-service/service/ServiceRequestModel').ServiceRequestModel;

/**
 * Create a service request browser
 *
 * @class Class implementing a simple service request web user interface
 * @constructor
 *
 * @param {Object} ui the ui object
 * @param {Number} one of ServiceRequestBrowser.MYREQUESTS, ServiceRequestBrowser.ASSIGNEDTOME or ServiceRequestBrowser.MEINVOLVEDIN
 */
function ServiceRequestBrowser(ui, selector) {
	this.ui = ui;
	this.service = ui.service;
	this.selector = selector;

	this.paginator = new Paginator();
	this.paginator.pageSize = 5;
	this.paginator.setOffset(-1);
}

exports.ServiceRequestBrowser = ServiceRequestBrowser;

ServiceRequestBrowser.MYREQUESTS = 1;		// Requests I initiated (originator == me)
ServiceRequestBrowser.REQUESTSFORME = 2;	// Requests I received (recipient == me)
ServiceRequestBrowser.ASSIGNEDTOME = 3;		// Requests assigned to a role I have (assignedToRole in my list of roles)
ServiceRequestBrowser.INVOLVESME = 4;		// Requests where I contributed (me in life-cycle changes)
ServiceRequestBrowser.PRINCIPALOUTREQUESTS = 5;	// Requests where I am the proxy of the subject originating the request
ServiceRequestBrowser.PRINCIPALINREQUESTS = 6;	// Requests where I am the proxy of the subject the request is directed to



ServiceRequestBrowser.prototype.getFilter = function() {
	var subjectId = this.ui.session.user.id;

	switch(this.selector) {
		case ServiceRequestBrowser.MYREQUESTS:
			var filter = { originatorId: subjectId };
			break;
		case ServiceRequestBrowser.REQUESTSFORME:
			var filter = { recipientId: subjectId };
			break;
		default:
			var filter = {};
	}

	return filter;
}



/**
 * Count request matching filter
 *
 * @returns the pending service requests
 * @type ServiceRequest[]
 */
ServiceRequestBrowser.prototype.countRequests = function() {
	var subjectId = this.ui.session.user.id;

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

	var filter = this.getFilter();

	switch(this.selector) {
		case ServiceRequestBrowser.MYREQUESTS:
		case ServiceRequestBrowser.REQUESTSFORME:
			var srs = srDAO.countServiceRequestsByFilter(filter);
			break;
		case ServiceRequestBrowser.ASSIGNEDTOME:
			var srs = srDAO.countServiceRequestsAssignedToSubjectsRoleByFilter(subjectId, filter);
			break;
		case ServiceRequestBrowser.INVOLVESME:
			break;
		case ServiceRequestBrowser.PRINCIPALOUTREQUESTS:
			break;
		case ServiceRequestBrowser.PRINCIPALINREQUESTS:
			break;
	}
	return srs;
}



/**
 * Enumerate all pending service requests to superior systems
 *
 * @returns the pending service requests
 * @type ServiceRequest[]
 */
ServiceRequestBrowser.prototype.listRequests = function(offset) {
	var subjectId = this.ui.session.user.id;

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

	var filter = this.getFilter();

	switch(this.selector) {
		case ServiceRequestBrowser.MYREQUESTS:
		case ServiceRequestBrowser.REQUESTSFORME:
			var list = srDAO.listServiceRequestsByFilter(filter, offset, this.paginator.pageSize);
			break;
		case ServiceRequestBrowser.ASSIGNEDTOME:
			var list = srDAO.listServiceRequestsAssignedToSubjectsRoleByFilter(subjectId, filter, offset, this.paginator.pageSize);
			break;
		case ServiceRequestBrowser.INVOLVESME:
			var list = srDAO.listServiceRequestsInvolvedBySubject(subjectId, filter, offset, this.paginator.pageSize);
			break;
		case ServiceRequestBrowser.PRINCIPALOUTREQUESTS:
			break;
		case ServiceRequestBrowser.PRINCIPALINREQUESTS:
			break;
	}

	return list;
}



ServiceRequestBrowser.prototype.setOffset = function(offset) {
	this.paginator.setOffset(offset);
}



ServiceRequestBrowser.prototype.setPageSize = function(pageSize) {
	this.paginator.pageSize = pageSize;
}



/**
 * Generate a table of certificates and the navigator elements
 *
 * @param {String} operations the operations part of the URL
 * @param {String} urlprefixholder the prefix to use for URLs addressing holder lists
 * @param {String} urlprefixlists the prefix to use for URLs addressing lists
 * @param {String} urlprefixcerts the prefix to use for URLs addressing certificates
 * @returns the table and navigator elements
 * @type XML
 */
ServiceRequestBrowser.prototype.renderServiceRequestTable = function(url) {
	default xml namespace = "http://www.w3.org/1999/xhtml";

	var records = this.countRequests();

	if (records == 0) {
		return;
	}

	switch(this.selector) {
		case ServiceRequestBrowser.MYREQUESTS:
		case ServiceRequestBrowser.REQUESTSFORME:
			var inout = "myrequest";
			break;
		case ServiceRequestBrowser.ASSIGNEDTOME:
			var inout = "inboundrequest";
			break;
		case ServiceRequestBrowser.INVOLVESME:
			break;
		case ServiceRequestBrowser.PRINCIPALOUTREQUESTS:
			break;
		case ServiceRequestBrowser.PRINCIPALINREQUESTS:
			break;
	}

	var srlist = this.listRequests(this.paginator.getOffset(records));

	var div = <div/>;

	var t = <table width="100%"><tr/></table>;

	var form =	<td><form action="" method="get" class="pure-form">
				<input name="op" type="hidden" value={ "changepagesize" + inout }/>
				<input name="pagesize" size="2" value={ this.paginator.pageSize }/>
				<button type="submit" class="pure-button">Entries per Page</button>
			</form></td>

	t.tr.appendChild(form);

	if (records > this.paginator.pageSize) {
		var pagenavigator = this.paginator.getPaginationStyle2(records, url + "?op=changeoffset" + inout + "&");
		t.tr.appendChild(pagenavigator);
	}

	div.appendChild(t);


	var t = <table class="pure-table pure-table-horizontal pure-table-striped"/>;

	t.tr += <tr><th width="10%">Id</th><th>Process</th><th>Status</th></tr>;

	for (var i = 0; i < srlist.length; i++) {
		var sr = srlist[i];

		var id = sr.id;
		var refurl = url + "/sr/" + id;
		var status = sr.state + " (" + sr.lifecycle + ")";
		var title = sr.title;
		if (sr.details) {
			title += " (" + sr.details + ")";
		}

		t.tr += <tr>
			<td><a href={refurl}>{id}</a></td>
			<td>{title}</td>
			<td>{status}</td>
		</tr>
	}

	div.appendChild(t);
	return div;
}



/**
 * Generate a table of certificates and the navigator elements
 *
 * @param {String} operations the operations part of the URL
 * @param {String} urlprefixholder the prefix to use for URLs addressing holder lists
 * @param {String} urlprefixlists the prefix to use for URLs addressing lists
 * @param {String} urlprefixcerts the prefix to use for URLs addressing certificates
 * @returns the table and navigator elements
 * @type XML
 */
ServiceRequestBrowser.prototype.renderServiceRequestList = function(url) {
	default xml namespace = "http://www.w3.org/1999/xhtml";

	var records = this.countRequests();

	if (records == 0) {
		return;
	}

	switch(this.selector) {
		case ServiceRequestBrowser.MYREQUESTS:
		case ServiceRequestBrowser.REQUESTSFORME:
			var inout = "myrequest";
			break;
		case ServiceRequestBrowser.ASSIGNEDTOME:
			var inout = "inboundrequest";
			break;
		case ServiceRequestBrowser.INVOLVESME:
			break;
		case ServiceRequestBrowser.PRINCIPALOUTREQUESTS:
			break;
		case ServiceRequestBrowser.PRINCIPALINREQUESTS:
			break;
	}

	var srlist = this.listRequests(this.paginator.getOffset(records));

	var div = <div class="sr-list"/>;

	var control = <div class="sr-list-control"/>;
	if (inout.equals("myrequest")) {
		control.appendChild(<h2>My Requests</h2>);
	} else if (inout.equals("inboundrequest")) {
		control.appendChild(<h2>Inbox</h2>);
	}

	var filter =
	<div class="sr-list-control-horizontal-menu pure-menu pure-menu-horizontal custom-restricted-width">

	</div>;

	var model = new MenuModel();

// 	TODO implement fucntionality in DAOs
// 	var filterModel = new MenuModel(<p class="no-margin">Filter</p>);
// 	filterModel.addItem(<a href="#">Ignore Completed Service Requests</a>);
// 	model.addItem(filterModel);
//
// 	var order = new MenuModel(<p class="no-margin">Order By</p>);
// 	order.addItem(<a href="#">Creation Date</a>);
// 	order.addItem(<a href="#">Edit Date</a>);
// 	order.addItem(<a href="#">Process</a>);
// 	model.addItem(order);

	var listSize = new MenuModel(<p class="no-margin">List Size</p>);
	listSize.addItem(<a href={"?op=changepagesize" + inout + "&pagesize=5"}>5</a>);
	listSize.addItem(<a href={"?op=changepagesize" + inout + "&pagesize=10"}>10</a>);
	listSize.addItem(<a href={"?op=changepagesize" + inout + "&pagesize=20"}>20</a>);
	listSize.addItem(<a href={"?op=changepagesize" + inout + "&pagesize=50"}>50</a>);
	listSize.addItem(<a href={"?op=changepagesize" + inout + "&pagesize=100"}>100</a>);
	model.addItem(listSize);

	var gen = new PureMenuGenerator();
	menu = gen.generateHorizontalMenu(model);

	filter.appendChild(menu);

	control.appendChild(filter);

	filter = <div class="sr-list-control-vertical-menu pure-menu pure-menu-horizontal"/>;
	filter.appendChild(menu);
	control.appendChild(filter);

	div.appendChild(control);

	for (var i = 0; i < srlist.length; i++) {
		var sr = srlist[i];

		var refurl = url + "/sr/" + sr.id;

		var entry = <div class="sr-list-entry pure-g"/>;

		var process = <div class="pure-u-1 pure-u-sm-4-5"/>;
		var details =
			<div class="pure-u-1 pure-u-sm-1-5">
				<ul>
					<!--<li style="word-break: break-all;">ID: {sr.id}</li>-->
					<li>ID: {sr.id}</li>
				</ul>
			</div>;

		var title = sr.title;
		if (sr.details) {
			title += " (" + sr.details + ")";
		}
		process.appendChild(<h3 class="no-margin">{title}</h3>);
		var state = sr.state + " (" + ServiceRequestModel.getLifeCycleStringForId(sr.lifecycle) + ")";

		process.appendChild(<p class="no-margin">{state}</p>);
		var created = new Date(sr.created);
		process.appendChild(<p class="no-margin">{created.toLocaleString()}</p>);

		entry.appendChild(process);
		entry.appendChild(details);

		div.appendChild(<a href={refurl}>{entry}</a>);
	}

	if (records > this.paginator.pageSize) {
		var pagenavigator = this.paginator.getPagination(records, url + "?op=changeoffset" + inout + "&");
		pagenavigator.@class = "sr-list-navigation";

		div.appendChild(pagenavigator)
	}

	return div;
}
