<?php
	namespace Mocha\Core;

	class InstanceKey
	{
		public $ClassIndex;
		public $InstanceIndex;
		public $IsDerived;
		
		public function __construct(int $class_id, int $inst_id, bool $isDerived = false)
		{
			$this->ClassIndex = $class_id;
			$this->InstanceIndex = $inst_id;
			$this->IsDerived = $isDerived;
		}

		public static function Parse(?string $instanceKeyStr) : ?InstanceKey
		{
			if ($instanceKeyStr !== null)
			{
				$sep = null;
				$isDerived = false;
				if (str_contains($instanceKeyStr, '$'))
				{
					$sep = '$';
				}
				else if (str_contains($instanceKeyStr, '!'))
				{
					$sep = '!';
					$isDerived = true;
				}
				if ($sep != null)
				{
					$split = explode($sep, $instanceKeyStr);
					if (count($split) == 2)
					{
						if (is_numeric($split[0]) && is_numeric($split[1]))
						{
							return new InstanceKey(intval($split[0]), intval($split[1]), $isDerived);
						}
					}
				}
			}
			return null;
		}
		public static function TryParse(?string $instanceKeyStr, ?InstanceKey &$out) : bool
		{
			$ik = InstanceKey::parse($instanceKeyStr);
			if ($ik !== null)
			{
				$out = $ik;
				return true;
			}
			return false;
		}

		public function __toString()
		{
			return $this->ClassIndex . "$" . $this->InstanceIndex;
		}
	}