<?php

	namespace Mocha\UI\Pages;
	
	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
	{
		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)
						{
							header("HTTP/1.1 200 OK");
							
							// 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));

							if ($command == "module/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("] }");
							}
							else
							{
								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;
		}
	}

?>