<?php

namespace Plainwork\UiAjax\Renderer;

use Plainwork\Http\Uri;
use Plainwork\Http\Request;
use Plainwork\Ui\Component\Main;
use Plainwork\Ui\Component\HtmlElement;

final class MainRendererDecorator
{
    public $uri = Uri::class;

    public function __invoke(Main $el, Request $request, callable $next)
    {
        if ($request->getAttribute('layoutId')) {
            return ($next)($el, $request);
        }

        $el->withJs('assets/plainwork/uiajax/ajax.js');
        $ret = ($next)($el, $request);

        $pathParam = $this->uri->getParamPrefix() . $this->uri->getPathParam();
        $layoutParam = $this->uri->getParamPrefix() . 'layout-';

        $ret = (new HtmlElement('div', $ret))
            ->withAttr('class', 'pw-ajax-container')
            ->withAttr('data-pw-path-param-name', $pathParam)
            ->withAttr('data-pw-layout-param-name', $layoutParam)
            ;

        return $ret;
    }
}
