<?php

namespace Plainwork\Ui\Renderer;

use Plainwork\Ui\Component\BlockList;
use Plainwork\Ui\Component\Table;
use Plainwork\Ui\Component\HtmlElement;

final class BlockListRenderer
{
    public function __invoke(BlockList $el)
    {
        $spacing = $el->getSpacing();
        $items = $el->getItems();
        if (!$items) {
            return;
        }

        if ($el->asTable) {
            $ret = (new Table());
            foreach ($items as $id => $item) {
                $ret->withCell($id, 1)->setContent($item);
            }

            return $ret;
        }

        if (count($items) < 2) {
            return current($items);
        }

        $ret = (new HtmlElement('div'))
            ->withAttr('class', 'pw-block-list')
            ;

        if (2 !== $spacing) {
            $ret->withAttr('class', 'pw-spacing-' . $spacing);
        }

        $attr = $el->getAttr();
        foreach ($attr as $k_ => $v_) {
            $ret->withAttr($k_, $v_);
        }

        foreach ($items as $item) {
            $v = (new HtmlElement('div'))
                ->append($item)
                // ->withAttr('style', ['border' => 'red 1px solid'])
                ;
            $ret->append($v);
        }

        foreach ($el->getChildren() as $child) {
            $ret->append($child);
        }

        return $ret;
    }
}
