<?php

namespace apexl\Io\modules\display\services;

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
{
    private const string DEFAULT_PAGE_KEY = 'default';

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

    public function registerDefault(Page $page): void
    {
        $this->registerPage(self::DEFAULT_PAGE_KEY, $page);
    }

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

    public function content($components, $page = null): Page
    {
        return $this->pages[$this->pageSetDataEvaluate($page)]->addToContent($components);
    }

    private function pageSetDataEvaluate($page): string
    {
        return $page ?? ($this->activePage ?? self::DEFAULT_PAGE_KEY);
    }

    public function setMetaAndPageTitle($title, $page = null): Page
    {
        $page = $this->pages[$this->pageSetDataEvaluate($page)];
        $page->setMetaTitle($title);
        $page->setPageTitle($title);

        return $page;
    }

    public function setMetaTitle($title, $page = null): Page
    {
        return $this->pages[$this->pageSetDataEvaluate($page)]->setMetaTitle($title);
    }

    public function setPageTitle($title, $page = null): Page
    {
        return $this->pages[$this->pageSetDataEvaluate($page)]->setPageTitle($title);
    }

    public function setMetaDescription($desc, $page = null): Page
    {
        return $this->pages[$this->pageSetDataEvaluate($page)]->setMetaDescription($desc);
    }

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

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

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

        return $page->getPage();
    }

    public function getPage($name): ?Page
    {
        return $this->pages[$name] ?? null;
    }

    //ensure we take the provided page first, and then fallback until we're on default.

    public function setActive($activePage): void
    {
        $this->activePage = $activePage;
    }
}
