<?php
	namespace Mocha\Search;
	use Mocha\Core\KnownClassGuids;
	
	class SearchHelper
	{
		/**
		 * @var \Mocha\Oms\MySQLDatabaseOms
		 */
		private $_OMS;
		public function __construct($oms)
		{
			$this->_OMS = $oms;
			$this->ValidClasses = [ ];
			$this->LastQuery = "";
		}

		public $ValidClasses;
		public $LastQuery;


		public function search(string $q)
		{
			if ($q == "")
				return $this->searchSlow($q);
			
			return $this->searchIndexed($q);
		}

		public function searchIndexed(string $q)
		{
			$oms = $this->_OMS;
			// $query = "SELECT DISTINCT src_inst_id FROM mocha_attributes WHERE att_value LIKE :att_value AND att_effective_date <= NOW() ORDER BY att_effective_date LIMIT 10";
			$query = <<<EOF
			SELECT DISTINCT mocha_instances.id, mocha_instances.class_id, mocha_instances.inst_id
			FROM mocha_instances, mocha_attributes
			WHERE mocha_instances.id = mocha_attributes.src_inst_id
			AND mocha_attributes.att_value LIKE :att_value
			EOF;

			$count = count($this->ValidClasses);
			if ($count > 0)
			{
				$query .= " AND (";
				for ($i = 0; $i < $count; $i++)
				{
					if ($this->ValidClasses[$i]->InstanceKey->InstanceIndex == 17)
					{
						$query .= " 1=1 ";
						continue;
					}

					$query .= "mocha_instances.class_id = " . $this->ValidClasses[$i]->InstanceKey->InstanceIndex;
					if ($i < $count - 1)
					{
						$query .= " OR ";
					}
				}
				$query .= ")";
			}
			$this->LastQuery = $query;

			$values = $oms->query($query, array
			(
				"att_value" => "%" . $q . "%"
			));

			$results = array();

			foreach ($values as $value)
			{
				$inst = $oms->getInstanceByDBID($value["id"]);
				/*
				foreach ($this->ValidClasses as $pclass)
				{
					if (!$oms->is_a($inst, $pclass))
						continue;
				}
				*/
				$title  = $oms->getInstanceText($inst);

				$searchResult = new SearchResult($inst, $title);
				$results[] = $searchResult;
			}

			return $results;
		}

		public function flattenValidClasses(array $validClasses)
		{
			$oms = $this->_OMS;
			$flattened = [ ];

			return $flattened;
		}

		public function searchSlow(string $query)
		{
			$oms = $this->_OMS;
			$insts = [];
			$validClasses = $this->ValidClasses;
			if (count($validClasses) === 0)
			{
				$validClasses = array
				(
					$oms->getInstanceByGlobalIdentifier(KnownClassGuids::Clasz),
					$oms->getInstanceByGlobalIdentifier(KnownClassGuids::Task)
				);
			}

			foreach ($validClasses as $validClass)
			{
				$insts2 = $oms->getInstancesOf($validClass);
				foreach ($insts2 as $inst2)
				{
					$insts[] = $inst2;
				}
			}

			$insts = array_unique($insts, SORT_REGULAR);

			$count = count($insts);
			$results = array();
			
			foreach ($insts as $inst)
			{
				$title  = $oms->getInstanceText($inst);
				if (!str_contains(strtolower($title), strtolower($query)))
				{
					continue;
				}

				$searchResult = new SearchResult($inst, $title);
				$results[] = $searchResult;
			}
			return $results;
		}
	}
?>