<?php

namespace Plainwork\UiWordPress\Renderer;

use Plainwork\Http\Request;
use Plainwork\Core\Translate;
use Plainwork\Http\Uri;
use Plainwork\Http\RequestFactory;
use Plainwork\Ui\Ui;
use Plainwork\Ui\HtmlHelper;
use Plainwork\Ui\Component\Link;
use Plainwork\Ui\Component\Menu;
use Plainwork\Ui\Component\TabMenu;
use Plainwork\Ui\Renderer\MenuRenderer;

class AdminMainMenuRenderer
{
    public $ui = Ui::class;
    public $uri = Uri::class;
    public Translate $translate;
    public $menuRenderer = MenuRenderer::class;
    public $requestFactory = RequestFactory::class;
    private $wpAdminPageSlug = 'sh5';

    public function __invoke(Menu $el, Request $request, callable $next)
    {
        $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) : [];

        $items = $el->getItems();

        $tabMenu = new TabMenu();

        $i = 0;
        foreach ($items as $item) {
            ++$i;
            $tabMenu->add($i, $item);

            if ($item instanceof Link) {
                $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;
                    }
                }
                if ($isOn) {
                    $tabMenu->setCurrent($i);
                }
            }
        }

        return $tabMenu;
    }
}
