<?php

namespace Plainwork\Ui\Renderer;

use Plainwork\Ui\Ui;
use Plainwork\Http\Request;
use Plainwork\Ui\Component\HtmlElement;
use Plainwork\Ui\Component\Menu;
use Plainwork\Ui\Component\Link;
use Plainwork\Ui\Renderer\MenuRenderer;

class MainMenuRenderer
{
    public $ui = Ui::class;
    public $menuRenderer = MenuRenderer::class;

    public function __invoke(Menu $el, Request $request)
    {
        $ret = '';

        $isPrintView = $this->ui->isPrintView();
        if ($isPrintView) {
            return $ret;
        }

        $items = $el->getItems();
        $items = array_filter($items, fn($e) => $this->menuRenderer->isItemAllowed($e, $request));
        if (!$items) {
            return $ret;
        }

        $currentPath = $request->getPath();
        // $currentPath = $el->getCurrentPath() ?? '';
        $currentPathArray = strlen($currentPath) ? explode('/', $currentPath) : [];

        $ret = new HtmlElement('ul');
        $ret->withAttr('class', 'pw-nav-topmenu');
        $ret->withAttr('class', 'pw-nav-inline');

        foreach ($items as $item) {
            $isOn = false;
            if ($item instanceof Link) {
                $item->setMenu(true);

                $path_ = $request->resolvePath($item->getPath());
                $pathArray_ = strlen($path_) ? explode('/', $path_) : [];

                $len = min(count($pathArray_), count($currentPathArray));
                $isOn = true;
                for ($i_ = 0; $i_ < $len; $i_++) {
                    if ($pathArray_[$i_] !== $currentPathArray[$i_]) {
                        $isOn = false;
                        break;
                    }
                }
            }

            $ret_ = new HtmlElement('li', $item);
            if ($isOn) {
                $ret_->withAttr('class', 'pw-nav-on');
            }
            $ret->append($ret_);
        }

        return $ret;
    }

}
