<?php

	namespace Mocha\UI\Pages;
	
	use Mocha\Core\InstanceKey;
	use Mocha\Core\InstanceReference;
	use Mocha\Core\KnownClassGuids;
	use Mocha\Core\KnownInstanceGuids;
	use Mocha\Core\KnownRelationshipGuids;
	use Mocha\UI\Controls\InstanceBrowser;
	use Phast\CancelEventArgs;
	use Phast\RenderingEventArgs;
	use Phast\System;
	use Phast\UUID;
	use Phast\WebPage;

	use Mocha\Search\SearchHelper;
	use Mocha\Search\SearchResult;


	class SearchPage extends WebPage
	{
		protected function OnRendering(RenderingEventArgs $re)
		{
			$query = $_GET["q"];
			
			$inst = null;
			if (InstanceKey::TryParse($query, $inst))
			{
				System::Redirect("~/d/inst/1\$" . $inst->ClassIndex . "/" . $inst->__toString() . ".htmld");
				$re->Handled = true;
				return false;
			}
			return true;
		}

		private function renderTaskResult(SearchResult $result)
		{
			?>
			<li class="uwt-menu-item uwt-menu-item-command uwt-visible">
				<a href="<?php echo (System::ExpandRelativePath("~/d/task/" . $result->Instance->InstanceKey . ".htmld")); ?>"><?php echo ($result->Title); ?></a>
			</li>
			<?php
		}

		protected function RenderContents()
		{
			?>
			<h1>Search Results</h1>
			<form method="GET">
				<input type="search" name="q" value="<?php echo($_GET["q"]); ?>" />
			</form>
			<?php
			if ($_GET["q"] != "")
			{
				?>
				<hr />
				<ul class="uwt-menu mcx-search-results" style="flex-grow: 1;">
				<?php
					/** @var \Mocha\Oms\MySQLDatabaseOMS */
					$oms = mocha_get_oms();

					$searchHelper = new SearchHelper($oms);
					$results = $searchHelper->search($_GET["q"]);

					// display tasks first
					$taskResults = [ ];
					foreach ($results as $result)
					{
						if ($oms->is_a($result->Instance, KnownClassGuids::Task))
						{
							$taskResults[] = $result;
						}
					}

					if (count($taskResults) > 0)
					{
						?>
						<li class="uwt-menu-item uwt-menu-item-header uwt-visible">Tasks</li>
						<?php
						foreach ($taskResults as $taskResult)
						{
							$this->renderTaskResult($taskResult);
						}
					}
					
					foreach ($results as $result)
					{
						?>
						<li class="uwt-menu-item uwt-menu-item-command uwt-visible">
						<?php
						$adw = new InstanceBrowser();
						$adw->SelectedInstances[] = $result->Instance;
						$adw->Render();
						?>
						</li>
						<?php
					}

				?>
				</ul>
				<?php
			}
		}
	}
	class SearchPageAPI extends WebPage
	{
		protected function OnInitializing(CancelEventArgs $e)
		{
			$this->Page->ContentType = "application/json";
			$this->Page->MasterPage->ClassReference->RequireLogin = false;
			return true;
		}
		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(value: $json));
				$re->Handled = true;
				return true;
			}

			$searchHelper = new SearchHelper($oms);

			$validClassIdsStr = $_GET["validClassIds"];
			if ($validClassIdsStr !== null && $validClassIdsStr !== "1$17")
			{
				$validClassIdsParm = explode(",", $_GET["validClassIds"]);
				$validClasses = [];
				foreach ($validClassIdsParm as $validClassIdParm)
				{
					$validClasses[] = $oms->getInstanceByKey(InstanceKey::parse($validClassIdParm));

					$instClass = $oms->getInstanceByKey(InstanceKey::parse($validClassIdParm));
					$subclasses = $oms->getRelatedInstances($instClass, KnownRelationshipGuids::Class__has_sub__Class);
					foreach ($subclasses as $subclass)
					{
						$validClasses[] = $subclass;
					}
				}
				$searchHelper->ValidClasses = $validClasses;
			}

			$query = $_GET["q"];
			$results = $searchHelper->search($query);
			$count = count($results);
			if ($count > 50)
			{
				if (strlen($query) < 3)
				{
					$json = array
					(
						"result" => "failure",
						"responseCode" => 400,
						"responseText" => "Bad Request",
	
						"mochaResponseCode" => "MCX0019",
						"mochaResponseText" => "Search Query Required",
						"title" => "Search Query Required",
						"message" => "Please enter a search query longer than 3 characters"
					);
					echo (json_encode($json));
					$re->Handled = true;
					return true;
				}
			}

			echo ("{ \"result\": \"success\", \"items\": [ ");
			for ($i = 0; $i < $count; $i++)
			{
				$inst = $results[$i]->Instance;
				$instClass = $oms->getParentClass($inst);
				$viewTask = $oms->getRelatedInstance($instClass, KnownRelationshipGuids::Class__has_default__Task);
				$uri = "/" . $oms->getTenantName() . "/d/inst/" . $inst->InstanceKey->__toString() . ".htmld";
				if ($oms->is_a($inst, KnownClassGuids::Task))
				{
					$uri = "/" . $oms->getTenantName() . "/d/task/" . $inst->InstanceKey->__toString() . ".htmld";
				}
				$instJson = array
				(
					"iconId" => null,
					"iid" => $inst->InstanceKey->__toString(),
					"imageUrl" => null,
					"label" => $results[$i]->Title,
					"title" => $results[$i]->Title,
					"subtitle1" => null,
					"subtitle2" => null,
					"subtitle3" => null,
					"summaryDescription" => $oms->getInstanceText($instClass),
					"returnedByQueryIntent" => false,
 					"viewTask" => $viewTask === null ? null : $viewTask->InstanceKey->__toString(),
					"uri" => $uri
				);
				echo (json_encode($instJson));
				if ($i < $count - 1)
				{
					echo(", ");
				}
			}
			echo (" ] }");

			$re->Handled = true;
			return true;
		}
	}

?>