<?php

namespace Plainwork\Ui\Renderer\Form;

use Plainwork\Http\Request;
use Plainwork\Ui\Component\Form\RadioInput;
use Plainwork\Ui\Component\HtmlElement;
use Plainwork\Ui\Component\InlineList;

final class RadioInputRenderer
{
    private static $htmlId = 1;

    public function __invoke(RadioInput $el, Request $request, callable $next)
    {
        $el = $el
            ->withTag('input')
            ->withAttr('type', 'radio')
            // ->withAttr('value', $el->getHtmlValue())
            ->withAttr('value', $el->getValue())
            ;

        // $val = $el->getValue();
        // if ($val) {
            // $el = $el->withAttr('checked', true);
        // }

        if ($el->isOn()) {
            $el = $el->withAttr('checked', true);
        }

        $label = $el->getLabel();
        if (null !== $label) {
            $htmlId = $el->getAttr('id');
            if (null === $htmlId) {
                $htmlId = 'pw-radio-' . static::$htmlId++;
                $el->withAttr('id', $htmlId);
            }
        }

        $ret = $next($el, $request);

        if (null !== $label) {
            $ret = (new HtmlElement('label'))
                ->withAttr('class', 'pw-wrapping-label')
                ->append($ret)
                ->append((new HtmlElement('span', $label))->withAttr('class', 'pw-nowrap'))
                ;
        }

        return $ret;
    }
}
