<?php
	namespace Mocha\Core;

	use Mocha\Core\Oms;

	use Mocha\Oop\Method;
	use Mocha\Oop\MethodBinding;

	use Phast\UUID;

	class InstanceReference
	{
		//public Oms $OMS;
		public ?int $DatabaseId;
		public InstanceKey|null $InstanceKey;
		public UUID|null $GlobalIdentifier;
		public string|null $Text;
		public InstanceReference|null $DefaultTask;
		public string|null $DefaultTaskUrl;
		public InstanceReference|null $ParentClass;

		public static function parse(array|null $obj) : InstanceReference|null
		{
			if ($obj == null)
				return null;

			return new InstanceReference(null, InstanceKey::parse($obj["iid"]), UUID::parse($obj["globalIdentifier"]), $obj["text"], InstanceReference::parse($obj["parentClass"]["defaultTask"]), InstanceReference::parse($obj["parentClass"]));
		}

		public static function toInstanceKeys(array $instanceReferences) : array
		{
			$keys = [ ];
			foreach ($instanceReferences as $instanceReference)
			{
				$keys[] = $instanceReference->InstanceKey;
			}
			return $keys;
		}

		public function __construct(?int $databaseId, InstanceKey|null $instanceKey, UUID|string|null $globalIdentifier, string|null $text = null, InstanceReference|string|null $defaultTaskOrUrl = null, InstanceReference|null $parentClass = null)
		{
			//$this->OMS = $oms;
			$this->DatabaseId = $databaseId;
			$this->InstanceKey = $instanceKey;

			if (is_string($globalIdentifier))
			{
				$globalIdentifier = UUID::parse($globalIdentifier);
			}
			$this->GlobalIdentifier = $globalIdentifier;
			$this->Text = $text;

			if (is_string($defaultTaskOrUrl))
			{
				$this->DefaultTaskUrl = $defaultTaskOrUrl;
				$this->DefaultTask = null;
			}
			else
			{
				$this->DefaultTask = $defaultTaskOrUrl;
				$this->DefaultTaskUrl = null;
			}
			$this->ParentClass = $parentClass;
		}

		/*
		public function getRelatedInstances(InstanceReference $relationship)
		{
			$instances = [];
			return $instances;
		}
		public function getAttributeValue($attributeInstance, $defaultValue = null, $effectiveDate = null) : ?string
		{
			return $this->OMS->getAttributeValue($this, $attributeInstance, $defaultValue, $effectiveDate);
		}

		*/

		public function asMethod()
		{
			return new Method($this);
		}
		public function asMethodBinding($oms)
		{
			return new MethodBinding($oms, $this);
		}

		public function __is_equal(InstanceReference $other)
		{
			return $this->GlobalIdentifier->__is_equal($other->GlobalIdentifier);
		}
		public function __is_not_equal(InstanceReference $other)
		{
			return !$this->__is_equal($other);
		}

		public function __toString()
		{
			if ($this === null)
			{
				// can we do this?
				return "(null)";
			}
			return $this->GlobalIdentifier->__toString() . " [" . $this->InstanceKey . "]";
		}
	}
?>