<?php

	namespace Mocha\UI\Pages;
	use Mocha\Core\InstanceKey;
	use Mocha\Core\InstanceReference;
	use Mocha\Core\KnownInstanceGuids;
	use Mocha\Core\KnownRelationshipGuids;
	use Mocha\Core\OmsContext;
	use Mocha\UI\Controls\InstanceBrowser;
	use Mocha\UI\Renderers\HTML\HTMLRenderer;
	use Phast\CancelEventArgs;
	use Phast\EventArgs;
	use Phast\QuickSort;
	use Phast\RenderingEventArgs;
	use Phast\System;
	use Phast\WebPage;

	class RelatedTaskListPage extends WebPage
	{

		private function getTaskUrl(InstanceReference $inst, InstanceReference $task)
		{
			return System::ExpandRelativePath("~/d/inst/" . $inst->InstanceKey . "/rel-task/" . $task->InstanceKey . ".htmld");
		}

		protected function RenderContents()
		{
			/** @var \Mocha\Oms\MySQLDatabaseOMS */
			$oms = mocha_get_oms();

			$tenant = $this->Page->GetPathVariableValue("tenant");
			$iid = $this->Page->GetPathVariableValue("instid");
			$inst = $oms->getInstanceByKey(InstanceKey::Parse($iid));
			$instParent = $oms->getParentClass($inst);

			$tasks = $oms->getRelatedTasks($inst);
			$taskDefs = [ ];
			
			$names = [ ];
			foreach ($tasks as $task)
			{
				$taskCategory = $oms->getRelatedInstance($task, KnownRelationshipGuids::Task__has__Task_Category);
				$name = $oms->getInstanceText($taskCategory);
				if (!in_array($name, $names))
				{
					$names[] = $name;
				}
				if (!array_key_exists($name, $taskDefs))
				{
					$taskDefs[$name] = array();
				}
				$taskDefs[$name][] = array ("title" => $oms->getInstanceText($task), "task" => $task);
			}

			natsort($names);

			echo ("<div style=\"width: 75%; margin-left: auto; margin-right: auto;\">");
			echo ("<h1>");
			$apb = new InstanceBrowser();
			$apb->SelectedInstances[] = $inst;
			$apb->Render();
			echo("</h1>");
			echo("<hr />");

			foreach ($names as $name)
			{
				echo ("<h2>" . $name . "</h2>");
				echo ("<ul class=\"uwt-menu\">");
				foreach ($taskDefs[$name] as $task)
				{
					echo ("<li class=\"uwt-menu-item uwt-menu-item-command uwt-visible\">");
					echo ("<a href=\""  . $this->getTaskUrl($inst, $task["task"]) . "\">" . $task["title"] . "</a>");
					echo ("</li>");
				}
				echo ("</ul>");
			}
			echo("</div>");
		}
	}

	class RelatedTaskListPageAPI extends WebPage
	{
		protected function OnInitializing(CancelEventArgs $e)
		{
			$this->Page->ContentType = "application/json";
			$this->Page->MasterPage->ClassReference->RequireLogin = false;
			return true;
		}

		private function createRelatedTask(InstanceReference $inst, InstanceReference $task)
		{
			/** @var \Mocha\Oms\MySQLDatabaseOMS */
			$oms = mocha_get_oms();

			$label = $oms->getInstanceText($task);

			$json = array
			(
				"widget" => "relatedTaskGroup",
				"tasks" => array
				(
					array
					(
						"widget" => "relatedTask",
						"uri" => System::ExpandRelativePath("~/d/inst/" . $inst->InstanceKey . "/rel-task/" . $task->InstanceKey . ".htmld"),
						"view" => true,
						"webService" => false,
						"iid" => $task->InstanceKey->__toString(),
						"label" => $label
					)
				)
			);
			return $json;
		}

		private function createTaskGroup($name, $taskGroup)
		{
			$json = array
			(
				"widget" => "relatedTaskGroup",
				"renderDifferently" => false,
				"taskGroups" => array
				(
					array
					(
						"widget" => "relatedTaskGroup",
						"label" => $name,
						"renderDifferently" => false,
						"taskGroups" => $taskGroup
					)
				)
			);
			return $json;
		}

		protected function OnRendering(RenderingEventArgs $re)
		{
			/** @var \Mocha\Oms\MySQLDatabaseOMS */
			$oms = mocha_get_oms();

			if ($oms->getCurrentUser() === null)
			{
				$json = array
				(
					"result" => "failure",
					"responseCode" => 403,
					"responseText" => "Forbidden",

					"title" => "Not Authorized",
					"message" => "Please log in to perform this action"
				);
				echo (json_encode($json));
				$re->Handled = true;
				return true;
			}

			$tenant = $this->Page->GetPathVariableValue("tenant");
			$iid = $this->Page->GetPathVariableValue("instid");
			$inst = $oms->getInstanceByKey(InstanceKey::Parse($iid));
			$instParent = $oms->getParentClass($inst);

			$tasks = $oms->getRelatedTasks($inst);
			$taskGroupsDefs = [ ];
			
			$names = [ ];
			foreach ($tasks as $task)
			{
				$taskCategory = $oms->getRelatedInstance($task, KnownRelationshipGuids::Task__has__Task_Category);
				$name = $oms->getInstanceText($taskCategory);
				if (!in_array($name, $names))
				{
					$names[] = $name;
				}
				if (!array_key_exists($name, $taskGroupsDefs))
				{
					$taskGroupsDefs[$name] = array();
				}
				$taskGroupsDefs[$name][] = $this->createRelatedTask($inst, $task);
			}

			natsort($names);

			$taskGroups = [ ];
			foreach ($names as $name)
			{
				$taskGroups[] = $this->createTaskGroup($name, $taskGroupsDefs[$name]);
			}

			$json = array
			(
				"widget" => "relatedTasks",
				"taskGroups" => $taskGroups,
				"instance" => array
				(
					"instanceId" => strval($inst->InstanceKey),
					"label" => $oms->getInstanceText($instParent),
					"title" => $oms->getInstanceText($inst)
				)
			);

			$previewElement = $oms->getRelatedInstance($instParent, KnownRelationshipGuids::Class__uses_preview__Executable_returning_Element);
			if ($previewElement !== null)
			{
				$ctx = new OmsContext();
				$parentECs = [ ];
				$r = new HTMLRenderer($ctx);
				$r->TargetInstance = $inst;
				$previewContent = $r->renderElementAsString($parentECs, $previewElement, [ $oms->getInstanceByGlobalIdentifier(KnownInstanceGuids::DisplayOption__Singular), $oms->getInstanceByGlobalIdentifier(KnownInstanceGuids::DisplayOption__ShowSubelementsVertically) ], true);
				$json["preview"] = $previewContent;
			}


			$json["result"] = "success";

			$messages = array();
			foreach ($oms->MetadataExceptions as $message)
			{
				$messages[] = array("title" => $message->Message, "content" => $message->Message, "severity" => $message->Severity);
			}
			$json["messages"] = $messages;

			echo(json_encode($json));
			$re->Handled = true;
		}

	}
?>