<?php

namespace Plainwork\UiWordPress\Renderer;

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

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

    public function __invoke(Main $el, Request $request, callable $next)
    {
// echo __METHOD__ . '<br>';
        $nextRet = ($next)($el, $request);

        if ($request->getAttribute('layoutId')) {
            return $nextRet;
        }

        $css = $el->getCss();
        array_unshift($css, 'assets/plainwork/ui/core.css');
        if (is_admin()) {
            $css[] = 'assets/plainwork/uiwordpress/admin.css';
        } else {
            $css[] = 'assets/plainwork/uiwordpress/front.css';
        }

        $wpStyles = [];
        foreach ($css as $f) {
            $assetId = 'plainware-' . $f;
            $assetUri = $this->uri->asset($f);
            wp_register_style($assetId, $assetUri);
            $wpStyles[] = $assetId;
        }
        foreach ($wpStyles as $assetId) {
            wp_enqueue_style($assetId);
        }

        $jss = $el->getJs();

        $wpScripts = [];
        foreach ($jss as $f) {
            $assetId = 'plainware-' . $f;
            $assetUri = $this->uri->asset($f);
            wp_register_script($assetId, $assetUri);
            $wpScripts[] = $assetId;
        }
        foreach ($wpScripts as $assetId) {
            wp_enqueue_script($assetId);
        }

        $wrapper = (new HtmlElement('div'))
            ->withAttr('class', 'wrap')
            ;
        $ret = $wrapper->append($nextRet);

        return $ret;
    }
}
