<?php

	namespace Mocha\UI\Pages;
	
	use Mocha\Core\InstanceKey;
	use Mocha\Core\KnownInstanceGuids;
	use Mocha\Core\KnownRelationshipGuids;

	use Mocha\Core\OmsContext;
	use Mocha\Oms\MySQLDatabaseOms;

	use Mocha\UI\Renderers\HTML\HTMLRenderer;
	use Phast\RenderingEventArgs;
	use Phast\WebPage;

	class InstancePage extends WebPage
	{

		protected function OnRendering(RenderingEventArgs $re)
		{
			parent::OnRendering($re);

			/**
			 * @var MySQLDatabaseOms
			 */
			$oms = mocha_get_oms();

			mocha_init_spot_timer($this->Page);

			$instIdCtl = $this->Page->GetControlByID("instId");
			$castIdCtl = $this->Page->GetControlByID("castId");
			
			$instkey = InstanceKey::Parse($this->Page->GetPathVariableValue("instid"));

			$castkey = InstanceKey::Parse($this->Page->GetPathVariableValue("castinstid"));
			if ($castIdCtl !== null)
			{
				if ($castkey === null)
				{
					$castIdCtl->Content = "invalid inst id " . $castkey . " (inst not found)";
				}
				else
				{
					$castIdCtl->Content = strval($castkey);
				}
			}

			$inst = $oms->getInstanceByKey($instkey);
			if ($inst === null)
			{
				$instIdCtl->Content = "invalid inst id " . $instkey . " (inst not found)";
			}
			else
			{
				$parentClass = $oms->getParentClass($inst);
				if ($castkey !== null)
				{
					$parentClass = $oms->getInstanceByKey($castkey);
				}
				
				$instIdCtl->Content = strval(($inst->InstanceKey));
				$rel_Class__has_default__Task = $oms->getInstanceByGlobalIdentifier(KnownRelationshipGuids::Class__has_default__Task);
				if ($rel_Class__has_default__Task !== null)
				{
					$defaultTask = $oms->getRelatedInstance($parentClass, $rel_Class__has_default__Task);
					if ($defaultTask !== null)
					{
						$context = new OmsContext();

						$context->setWorkData(KnownInstanceGuids::WorkSet__RelatedInstance, $inst);

						$taskRenderer = new HTMLRenderer($context);
						$taskRenderer->TargetInstance = $inst;
						$taskRenderer->IsPostback = $this->Page->IsPostback;
						if ($this->IsPostback)
						{
							$taskRenderer->processPostback($defaultTask);
						}
						else
						{
							$taskRenderer->renderTask($defaultTask, $inst);
						}
						exit();
					}
				}
			}
		}

	}
?>