<?php

	namespace Mocha\UI\Pages;
	
	use Mocha\Core\InstanceKey;
	use Mocha\Core\KnownClassGuids;
	use Mocha\Core\KnownInstanceGuids;
	use Mocha\Core\KnownRelationshipGuids;
	use Mocha\Search\SearchHelper;
	use Phast\RenderingEventArgs;
	use Phast\System;
	use Phast\WebPage;

	class PromptPage extends WebPage
	{
		protected function OnRendering(RenderingEventArgs $re)
		{
			/**
			 * @var \Mocha\Oms\MySQLDatabaseOms
			 */
			$oms = mocha_get_oms();

			$tenant = $this->Page->GetPathVariableValue("tenant");
			$context = $this->Page->GetPathVariableValue("context");
			$id = $this->Page->GetPathVariableValue("id");
			
			// header($_SERVER["SERVER_PROTOCOL"] . " 200 OK");
			header("Content-Type: application/json");

			$json = [
				"widget" => "prompt",
				"promptUriTemplate" => "/" . $oms->getTenantName() . "/prompt/[CONTEXT_ID]/[PROMPT_IID]",
				"searchable" => true,
				"instances" => [
					[
						"instanceId" => "45$1740",
						"text" => "All",
						"current" => true
					]
				],
				"items" => [ ]
			];

			$search = new SearchHelper($oms);

			$ec = $oms->getInstanceByKey(InstanceKey::Parse($id));
			if ($ec !== null)
			{
				$ecinst = $oms->getRelatedInstance($ec, KnownRelationshipGuids::Element_Content__has__Instance);
				if ($ecinst !== null)
				{
					if ($oms->is_a($ecinst, KnownClassGuids::Clasz))
					{
						$search->ValidClasses[] = $ecinst;
					}
					else if ($oms->is_a($ecinst, KnownClassGuids::Relationship))
					{
						$relDestination = $oms->getRelatedInstance($ecinst, KnownRelationshipGuids::Relationship__has_destination__Class);
						$search->ValidClasses[] = $relDestination;
					}
				}
			}

			$postdata = file_get_contents("php://input");
			$postjson = json_decode($postdata, true);

			$query = "";
			if (isset($postjson["q"]))
			{
				$query = $postjson["q"];
			}

			$json["q"] = $query;
			$results = $search->search($query);
			$json["query"] = $search->LastQuery;
			
			foreach ($results as $result)
			{
				$viewTaskIid = null;
				$viewTask  =$oms->getRelatedInstance($oms->getParentClass($result->Instance), KnownRelationshipGuids::Class__has_default__Task);
				if ($viewTask !== null)
				{
					$viewTaskIid = $viewTask->InstanceKey->__toString();
				}

				$json["items"][] = [
					"instanceId" => $result->Instance->InstanceKey->__toString(),
					"text" => $result->Title,
					"action" => "view",
					"viewTask" => $viewTaskIid
				];
			}
			echo (json_encode($json));

			$re->Cancel = true;
		}
	}

?>