<?php

namespace Plainwork\Ui\Renderer\Form;

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

final class CheckboxInputRenderer
{
    private static $htmlId = 1;

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

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

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

            $attr = $el->getAttr();
            if (isset($attr['class'])) {
                $attrClass = $attr['class'];
                $el->unsetAttr('class');
            }
            $attr = $el->getAttr();
            // _print_r($attr);
            // exit;
        }

        $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'))
                ;
            if ($attrClass) {
                $ret->withAttr('class', $attrClass);
            }
        }

        return $ret;
    }
}
