<?php

namespace Plainwork\Ui\Renderer\Form;

use Plainwork\Ui\Component\HtmlElement;
use Plainwork\Ui\Component\Card;
use Plainwork\Ui\Component\InlineList;
use Plainwork\Ui\Component\BlockList;
use Plainwork\Ui\Component\Form\CheckboxSetInput;
use Plainwork\Ui\Component\Form\CheckboxInput;

final class CheckboxSetInputRenderer
{
    public function __invoke(CheckboxSetInput $el)
    {
        $options = $el->getOptions();
        if ($el->isRequired() && (count($options) < 2)) {
            $ret = new Card(current($options));

            return $ret;
        }

        $name = $el->getName();
        $value = $el->getValue();
        $disabledOptions = $el->getDisabledOptions();

        if ($el->isVertical) {
            $ret = (new BlockList())->setSpacing(2);
        } else {
            $ret = (new InlineList())->setSpacing(2);
        }

        foreach ($options as $k => $label) {
            if (in_array($k, $disabledOptions)) {
                $one = new HtmlElement('del', $label);
            } else {
                $one = (new CheckboxInput($name . '[]'))
                    ->setHtmlValue($k)
                    ;
                $one->setLabel($label);
                if (in_array($k, $value)) {
                    $one->setValue(true);
                }
            }
            $ret->add($one);
        }

        $ret = (new HtmlElement('fieldset', $ret));

        return $ret;
    }
}
