<?php

namespace Planaday\Utility\FormBuilder\LayoutItems;

use Planaday\Utility\DataGrouping\UUIDGenerator;
use Planaday\Utility\FormBuilder\Condition;
use Planaday\Utility\FormBuilder\Form;
use Planaday\Utility\FormBuilder\LayoutItem;

trait BasicLayoutItem {
	protected ?LayoutItem $parent = null;
	protected ?Form $owner = null;
	protected string $itemId;
	/** @var Condition[] */
	protected array $conditions = [];

	public function getParent(): ?LayoutItem {
		return $this->parent;
	}

	public function setParent( ?LayoutItem $parent ): static {
		$this->parent = $parent;
		$this->owner = $parent->getOwner();
		return $this;
	}

	public function getOwner(): ?Form {
		return $this->owner;
	}

	public function addConditions(Condition ...$conditions): static {
		$this->conditions = array_merge($this->conditions, $conditions);
		return $this;
	}

	protected function validateConditions(): bool {
		foreach ($this->conditions as $condition) {
			if (!$condition->check()) {
				return false;
			}
		}
		return true;
	}

	public function getItemId(): string {
		if ( !isset( $this->itemId ) ) {
			$this->itemId = UUIDGenerator::generateUUIDv4OrRandom();
		}
		return $this->itemId;
	}

	public function jsonSerialize(): array {
		return [
			"type" => 'LayoutItem',
			"id" => $this->getItemId(),
			"impl" => $this->getImplJson(),
			"conditions" => $this->conditions,
		];
	}

	protected abstract function getImplJson(): mixed;
}