<?php

namespace Plainwork\Ui\Renderer;

use Plainwork\Http\Request;
use Plainwork\Http\Router;
use Plainwork\Ui\Component\Collection;
use Plainwork\Ui\Component\HtmlElement;
use Plainwork\Ui\Component\InlineList;
use Plainwork\Ui\Component\BlockList;
use Plainwork\Ui\Component\Menu;
use Plainwork\Ui\Component\Partial;
use Plainwork\Ui\PageMap;
use Plainwork\Ui\Ui;

final class PartialRenderer
{
    public $ui = Ui::class;
    public $pageMap = PageMap::class;
    public $router = Router::class;

    public function __invoke(Partial $el, Request $request)
    {
        $path = $request->getPath();

        $hash = $el->getHash();
        list($hashPattern, $hashParams) = $this->pageMap->parseHash($hash);
        foreach ($hashParams as $k => $v) {
            $request = $request->withRouteParam($k, $v);
        }

        $ret = [];

        $content = $el->getContent();
        if (null === $content) {
            $content = $this->pageMap->getPartialContent($path, $hash);
        }
        $content = $this->ui->render($content, $request);
        if (null === $content) {
            return;
        }

        if ($content) {
            $ret[] = [PageMap::POS_CONTENT, $content];
        }

        // echo "PARTIAL '$route#$hash'<br>";
        // echo "PARSED '$routePattern#$hashPattern'<br>";

    // GET MENUS
        $menus = [];
        $menuItems = $this->pageMap->getPartialMenuItems($path, $hash);
        foreach ($menuItems as $pos_ => $items_) {
            if ($items_) {
                $ret_ = new Menu();
                foreach ($items_ as $item) {
                    $ret_->add($item);
                }
                $ret_ = $this->ui->render($ret_, $request);
                if (strlen($ret_)) {
                    $menus[$pos_] = $ret_;
                }
            }
        }

    // BUILD: TITLE
        $title = $el->getTitle();
        if (null === $title) {
            $title = $this->pageMap->getPartialTitle($path, $hash);
        }
        if ($title) {
            $title = $this->ui->render($title, $request);
            if (strlen($title)) {
                $pos_ = PageMap::POS_TITLE;
                $ret_ = (new HtmlElement('h2'))->append($title);
                if (isset($menus[$pos_])) {
                    $ret_ = new InlineList([$ret_, $menus[$pos_]]);
                    unset($menus[$pos_]);
                }
                $ret[] = [$pos_, $ret_];
            }
        }

    // BUILD: MENUS
        foreach ($menus as $pos_ => $ret_) {
            $ret[] = [$pos_, $ret_];
        }

        if (!$ret) {
            return;
        }

        usort($ret, fn($a, $b) => $a[0] - $b[0]);
        $ret = array_column($ret, 1);

        $ret_ = (new BlockList())->setSpacing(2);
        foreach ($ret as $v) {
            $ret_->add($v);
        }

        return $ret_;
    }
}
