<?php

namespace Plainwork\Ui\Renderer;

use Plainwork\Ui\Component\Grid;
use Plainwork\Ui\Component\HtmlElement;

final class GridRenderer
{
    public function __invoke(Grid $el)
    {
        $items = $el->getItems();
        if (!$items) {
            $ret = '';
            return $ret;
        }

        $spacing = $el->getSpacing();

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

        $attr = $el->getAttr();
        foreach ($attr as $k => $v) {
            $ret->withAttr($k, $v);
        }
        if ($el->isAlignCenter()) {
            $ret->withAttr('class', 'pw-col-align-center');
        }

        $scheme = $el->getScheme();
        if (12 === $scheme) {
            $cssClass = 'pw-grid-12';
        } elseif (false !== strpos($scheme, '-')) {
            $cssClass = 'pw-grid-' . $scheme;
        } else {
            $cssClass = 'pw-grid-' . join('-', str_split((string) $scheme));
        }
        $ret->withAttr('class', $cssClass);

        foreach ($items as $item) {
            $ret->append(new HtmlElement('div', $item));
        }

        return $ret;
    }
}
