<?php

namespace Plainwork\Ui\Renderer;

use Plainwork\Http\Request;
use Plainwork\Ui\Ui;
use Plainwork\Ui\Html;
use Plainwork\Ui\Component\TabMenu;
use Plainwork\Ui\Component\Link;
use Plainwork\Ui\Renderer\MenuRenderer;

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

    public function __invoke(TabMenu $el, Request $request): string
    {
        $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;
        }

        $ret = [];
        $ret[] = '<div class="pw-header-tabmenu">';
        $ret[] = '<ul class="pw-nav-tab">';

        $currentItemId = $el->getCurrent();


        foreach ($items as $itemId => $item) {
            $v = $this->ui->render($item, $request);
            if (!strlen($v)) {
                continue;
            }

            $isOn = ($itemId == $currentItemId) ? true : false;

            $ret[] = '<li';
            $attr = [];
            if ($isOn) {
                $attr['class'] = 'pw-nav-on';
            }
            if ($attr) {
                $ret[] = ' ' . Html::attr($attr);
            }
            $ret[] = '>';

            if ($item instanceof Link) {
                $ret[] = $v;
            } else {
                $ret[] = '<span>';
                $ret[] = $v;
                $ret[] = '</span>';
            }

            $ret[] = '</li>';
        }
        $ret[] = '</ul>';
        $ret[] = '</div>';

        $ret = join('', $ret);

        return $ret;
    }
}
