<?php

	namespace Mocha\UI\Pages;

	use Mocha\Core\InstanceKey;
	
	use Mocha\Core\InstanceReference;
	use Mocha\Core\KnownAttributeGuids;
	use Mocha\Core\KnownClassGuids;
	use Mocha\Core\KnownInstanceGuids;
	use Mocha\Core\KnownRelationshipGuids;
	use Phast\RenderingEventArgs;
	use Phast\System;
	use Phast\WebPage;

	class OTSPage extends WebPage
	{
		private $EntityDefinitions;
		private $EntityDefinitions2;

		public function __construct()
		{
			parent::__construct();
			

			$this->EntityDefinitions = array
			(

			);
			$this->EntityDefinitions2 = array
			(
				"98cc2a320289406e8df45e154ca601d2" => "IDC_CircuitBreakerPanel",
				"89102e1cc3144a5fa752aa84e05ca83f" => "IDI_CircuitBreakerPanel_CarmelBay"
			);
		}

		private function zqGetClassName(InstanceReference $i)
		{
			$oms = mocha_get_oms();

			$key = $i->GlobalIdentifier->__toStringFormat(false, "", "");
			if (array_key_exists($key, $this->EntityDefinitions2))
			{
				return "&" . $this->EntityDefinitions2[$key] . ";";
			}
			else
			{
				$name = $oms->getAttributeValue($i, KnownAttributeGuids::Name);
				$name = str_replace(" ", "", $name);
				return "&IDC_" . $name . ";";
			}
			return $i->GlobalIdentifier->__toString();
		}

		protected function OnRendering(RenderingEventArgs $re)
		{
			parent::OnRendering($re);
			
			$path = System::GetVirtualPath();
			$tenantName = null;
			if (count($path) >= 3)
			{
				$tenantName = $path[1];
			}
			
			if ($tenantName === null)
			{
				header("HTTP/1.1 404 Not Found");
				header("Content-Type: text/plain");
				echo ("\" Not Available \"");
				die();
			}
			else
			{
				$oms = mocha_get_oms();
				if ($oms != null)
				{
					$ti = $oms->getTenantByName($tenantName);
					if ($ti === null)
					{
						header("HTTP/1.1 404 Not Found");
						header("Content-Type: text/plain");
						echo("The requested resource could not be found.");
						die();
					}
					else
					{
						if (count($path) >= 5)
						{
							// e.g. https://i-0c0398f84acecb702.privatesuv.com/ots/super/services/zq/v1/module/list

							// ots/{tenant}/services/{serviceName}/{version}/{command}
							$tenantName = $this->Page->GetPathVariableValue("tenant");
							$serviceName = $this->Page->GetPathVariableValue("serviceName");
							$version = $this->Page->GetPathVariableValue("version");
							$command = $this->Page->GetPathVariableValue("command");

							$oms->setTenant($oms->getTenantByName($tenantName));

							$instClass = $oms->getInstanceByGlobalIdentifier(KnownClassGuids::Clasz);
							$instances = $oms->getRelatedInstances($instClass, $oms->getInstanceByGlobalIdentifier(KnownRelationshipGuids::Class__has__Instance));

							$cmdparts = explode("/", $command);
							if (count($cmdparts) >= 2)
							{
								if ($cmdparts[0] === "instance")
								{
									$ik = InstanceKey::Parse($cmdparts[1]);
									if ($ik === null)
									{
										header("HTTP/1.1 404 Not Found");
										header("Content-Type: text/plain");
										echo("invalid inst id " . $cmdparts[1]);
										die();
									}

									$ir = $oms->getInstanceByKey($ik);
									header("HTTP/1.1 200 OK");
									header("Content-Type: text/plain");

									echo ("- library: '&IDL_MochaBaseSystem;'\n");
									echo ("  instances:\n");

									
									if ($ik->ClassIndex == 1)
									{
										echo ("  - class: '" . $this->zqGetClassName($ir) . "'\n");
									}
									else
									{
										echo ("  - instance: '" . $this->zqGetClassName($ir) . "'\n");
									}

									//$attrs = $oms->getRelatedInstances($ir, KnownRelationshipGuids::Class__has__Attribute);
									$attrs = $oms->getAttributes($ir);
									if (count($attrs) > 0)
									{
										echo ("  - attributes:\n");
										foreach ($attrs as $attr)
										{
											echo ("    - instance: '" . $attr->GlobalIdentifier . "'\n");
											echo ("    - value: '" . $oms->getAttributeValue($ir, $attr) . "'\n");
										}
									}

									$rels = $oms->getRelationships($ir);
									if (count($rels) > 0)
									{
										echo ("  - relationships:\n");
										foreach ($rels as $rel)
										{
											$gid = $rel->GlobalIdentifier->__toString();
											if (array_key_exists($rel->GlobalIdentifier->__toStringFormat(false, "", ""), $this->EntityDefinitions2))
											{
												$gid = "&" . $this->EntityDefinitions2[$rel->GlobalIdentifier->__toStringFormat(false, "", "")] . ";";
											}
											echo ("    - instance: '" . $rel->GlobalIdentifier . "'\n");
											$targs = $oms->getRelatedInstances($ir, $rel);
											if (count($targs) > 0)
											{
												echo ("      targetInstances:\n");
											}
											foreach ($targs as $targ)
											{
												$iid = $targ->GlobalIdentifier->__toString();
												if (array_key_exists($targ->GlobalIdentifier->__toStringFormat(false, "", ""), $this->EntityDefinitions2))
												{
													$iid = "&" . $this->EntityDefinitions2[$targ->GlobalIdentifier->__toStringFormat(false, "", "")] . ";";
												}
												
												echo ("      = instance: '" . $iid . "'\n");
											}
										}
									}


									$defaultTask = $oms->getRelatedInstance($ir, KnownRelationshipGuids::Class__has_default__Task);
									if ($defaultTask !== null)
									{
										echo ("  - defaultTask: '" . $defaultTask->GlobalIdentifier . "'\n");
									}

									$relTasks = $oms->getRelatedINstances($ir, KnownRelationshipGuids::Class__has_related__Task);
									if (count($relTasks) > 0)
									{
										echo ("  - relatedTasks:\n");
										foreach ($relTasks as $relTask)
										{
											echo ("    - instance: '" . $relTask->GlobalIdentifier . "'\n");
										}
									}
									$re->Cancel = true;
									return;
								}
								else if ($cmdparts[0] === "module")
								{
									if ($cmdparts[1] === "list")
									{
										header("Content-Type: application/json");
										print("{ \"items\": [ ");
										print("{ \"name\": \"mocha\", \"title\": \"mocha\", \"type\": \"module\", \"items\": [ ");

										$ct = count($instances);
										for ($i = 0; $i < $ct; $i++)
										{
											print("{ \"name\": \"mocha:inst" . $i . "\", \"title\": \"" . $oms->getInstanceText($instances[$i]) . "\", \"type\": \"class\", \"instanceId\": \"" . $instances[$i]->InstanceKey . "\" }");
											if ($i < $ct - 1)
											{
												print(", ");
											}
										}

										print("] }");
										print("] }");
										return;
									}
								}
							}
							
							header("HTTP/1.1 501 Not Implemented");
							header("Content-Type: text/plain");
							print("tenantName: " . $tenantName . "\n");
							print("serviceName: " . $serviceName . "\n");
							print("version: " . $version . "\n");
							print("command: " . $command . "\n");
							die();
						}
						else
						{
							header("HTTP/1.1 404 Not Found");
							header("Content-Type: text/plain");
							echo("The requested resource could not be found.");
							die();
						}
					}
				}
			}
			
			$re->Cancel = true;
		}
	}

?>