<?php
	namespace Mocha\Oop\MethodImplementations;

	use Mocha\Core\InstanceReference;
	use Mocha\Core\KnownAttributeGuids;
	use Mocha\Core\KnownClassGuids;
	use Mocha\Core\KnownInstanceGuids;
	use Mocha\Core\KnownRelationshipGuids;
	use Mocha\Core\OmsContext;
	use Mocha\Oms\Oms;
	use Mocha\Oop\MethodImplementation;

	use Phast\UUID;

	class GetInstanceSetBySystemRoutineMethodImplementation extends MethodImplementation
	{
		protected function executeInternal(Oms $oms, OmsContext $context, InstanceReference $method, ?array $parms)
		{
			$instSystemRoutine = $oms->getRelatedInstance($method, $oms->getInstanceByGlobalIdentifier(KnownRelationshipGuids::Get_Instance_Set_by_System_Routine_Method__uses__System_Instance_Set_Routine));
			echo ("exec sys routine " . $instSystemRoutine->GlobalIdentifier);
			$returnsWorkData = $oms->getRelatedInstance($method, KnownRelationshipGuids::Get_Instance_Set_by_System_Routine_Method__returns__Instance_Set);
			$singular = $oms->getAttributeValue($instSystemRoutine, $oms->getInstanceByGlobalIdentifier(KnownAttributeGuids::Singular));
			$value = null;

			if ($instSystemRoutine->GlobalIdentifier->__is_equal(UUID::parse(KnownInstanceGuids::SystemInstanceSetRoutine_CreateInstance)))
			{
				$clasz = $context->getWorkData(KnownInstanceGuids::WorkSet__ClassOfInstanceToCreate);
				if (is_array($clasz))
				{
					$clasz = $clasz[0];
				}

				$inst = $oms->createInstanceOf($clasz);
				$value = $inst;
				echo ("create instance of " . $clasz . " = " . $inst . " , returned in " . $returnsWorkData);
			}
			else if ($instSystemRoutine->GlobalIdentifier->__is_equal(UUID::parse(KnownInstanceGuids::SystemInstanceSetRoutine_GetUserForUserNameParm)))
			{
				// get User for User Name parm
				// this System Attribute Routine has a required parm: `User Name [TX]` [4$11]
				$userName = $context->getWorkData(KnownAttributeGuids::UserName); // $parms[KnownAttributeGuids::UserName];
				$value = $oms->getUserByUserName($userName);
			}

			if (is_array($value) && $singular)
			{
				$value = $value[0];
			}
			else if (!is_array($value) && !$singular)
			{
				$value = [ $value ];
			}
			$context->setWorkData($returnsWorkData, $value);
			
			return $returnsWorkData;
		}
	}

?>