<?php
	namespace Mocha\Oop\MethodImplementations;

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

	class ConditionalSelectAttributeMethodImplementation extends MethodImplementation
	{
		protected function executeInternal(Oms $oms, OmsContext $context, InstanceReference $method, ?array $parms)
		{
			$retval = null;
			$returnsAttribute = $oms->getRelatedInstance($method, KnownRelationshipGuids::Conditional_Select_Attribute_Method__returns__Attribute);
			$cases = $oms->getRelatedInstances($method, KnownRelationshipGuids::Conditional_Select_Attribute_Method__has__Conditional_Select_Attribute_Case);
			foreach ($cases as $case)
			{
				$trueConditions = $oms->getRelatedInstances($case, KnownRelationshipGuids::Condition_Group__has_true_condition__Executable_returning_Attribute);
				$falseConditions = $oms->getRelatedInstances($case, KnownRelationshipGuids::Condition_Group__has_false_condition__Executable_returning_Attribute);
				if (!$oms->evaluateConditions($context, $trueConditions, $falseConditions))
				{
					continue;
				}

				$invokesExecutableReturningAttribute = $oms->getRelatedInstance($case, KnownRelationshipGuids::Conditional_Select_Attribute_Case__invokes__Executable_returning_Attribute);
				if ($invokesExecutableReturningAttribute !== null)
				{
					$att = $oms->execute($context, $invokesExecutableReturningAttribute);
					return $att;
				}
				else
				{
					$pp = $oms->getInstanceByGlobalIdentifier(KnownAttributeGuids::Value);
					$context->setWorkData($pp, "SAC case with NULL attribute");
					$retval = $pp;
				}
			}
			if ($retval === null)
			{
				$pp = $oms->getInstanceByGlobalIdentifier(KnownAttributeGuids::Value);
				$context->setWorkData($pp, "SAC returned no case");
				$retval = $pp;
			}
			return $retval;
		}
	}

?>