<?php

class ModulesWrapper implements ArrayAccess
{
    private static $instance;

    public function offsetSet($offset, $value): void
    {
        throw new \BadMethodCallException();
    }

    public function offsetExists($offset): bool
    {
        return true;
    }

    public function offsetUnset($offset): void
    {
        throw new \BadMethodCallException();
    }

    public function offsetGet($offset): mixed
    {
        $parts = explode('__', $offset);

        $module = $parts[0];
        $submodule = getVal(1, $parts);

        $module_const = '\Modules::'.$module;
        $submodule_const = null;

        if (!defined($module_const)) {
            throw new \InvalidArgumentException("Module {$module} is not defined");
        }

        if ($submodule) {
            $submodule_const = '\Modules::SUB_'.$submodule;

            if (!defined($submodule_const)) {
                throw new \InvalidArgumentException("Submodule {$module}:{$submodule} is not defined");
            }
        }

        return findModule(constant($module_const), $submodule ? constant($submodule_const) : null);
    }

    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = new static();
        }

        return self::$instance;
    }
}
