<?php declare(strict_types = 1);

namespace idoit\Module\SyneticsFlows\Template\TemplateVariables;

class ObjectAccessTemplate
{
    private ?CategoryDataTemplate $data = null;

    /**
     * @var array<string, CategoryDataTemplate>
     */
    private ?array $categories = [];

    public function getCategory(string $name): ?CategoryDataTemplate
    {
        if (!str_starts_with($name, 'C__CAT')) {
            return null;
        }

        if (!isset($this->categories[$name])) {
            $this->categories[$name] = new CategoryDataTemplate($name, $this->objectId);
        };
        return $this->categories[$name];
    }

    public function __construct(private string $objectId)
    {
    }

    private function resolveObjectData(): void
    {
        if (!$this->data) {
            $this->data = $this->getCategory('C__CATG__GLOBAL');
        }
    }

    public function __get(string $name)
    {
        $this->resolveObjectData();
        if ($name === 'data') {
            return $this->data;
        }
        if (isset($this->data->$name)) {
            return $this->data->$name;
        }
        return $this->getCategory($name);
    }

    public function __isset(string $name): bool
    {
        if ($name === 'data') {
            return true;
        }
        $this->resolveObjectData();
        if (isset($this->data->$name)) {
            return true;
        }

        return $this->getCategory($name) !== null;
    }

    public function __toString(): string
    {
        $this->resolveObjectData();
        return json_encode($this->data->at(0), JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT | JSON_FORCE_OBJECT);
    }
}
