<?php

namespace apexl\Io\modules\display\services;

use apexl\ClassEngine\EngineSingleton;
use apexl\Io\modules\component\entities\componentEntity;
use apexl\Io\modules\display\includes\Page;

/**
 * Class Render
 * Provides a global render store for pages.
 * Allows various projects to manipulate the default display output of modules
 * @package apexl\Io\modules\page\services
 */
class Render extends EngineSingleton
{
    private const DEFAULT_PAGE_KEY = 'default';

    /**
     * @var array<string, Page>
     */
    protected static array $pages = [];
    protected static string $activePage = self::DEFAULT_PAGE_KEY;

    public static function setActive($activePage): void
    {
        self::$activePage = $activePage;
    }

    public static function registerDefault(Page $page): void
    {
        self::$pages[self::DEFAULT_PAGE_KEY] = $page;
    }

    public static function registerPage(string $name, Page $page): void
    {
        self::$pages[$name] = $page;
    }

    public static function content($components, $page = self::DEFAULT_PAGE_KEY): Page
    {
        return self::$pages[$page]->addToContent($components);
    }

    public static function setMetaAndPageTitle($title, $page = self::DEFAULT_PAGE_KEY): Page
    {
        $page = self::$pages[$page];
        $page->setMetaTitle($title);
        $page->setPageTitle($title);

        return $page;
    }

    public static function setMetaTitle($title, $page = self::DEFAULT_PAGE_KEY): Page
    {
        return self::$pages[$page]->setMetaTitle($title);
    }

    public static function setPageTitle($title, $page = self::DEFAULT_PAGE_KEY): Page
    {
        return self::$pages[$page]->setPageTitle($title);
    }

    public static function setMetaDescription($desc, $page = self::DEFAULT_PAGE_KEY): Page
    {
        return self::$pages[$page]->setMetaDescription($desc);
    }

    /**
     * @param  componentEntity[]|componentEntity|null  $components
     */
    public static function build(array|componentEntity|null $components = null): array
    {
        $page = self::getPage(self::$activePage);

        if (!$page) {
            return [];
        }

        if ($components) {
            if ($components instanceof componentEntity) {
                $components = [$components];
            }
            $page->addToContent($components);
        }

        return $page->getPage();
    }

    public static function getPage($name): ?Page
    {
        return self::$pages[$name] ?? null;
    }
}
