<?php

namespace Plainwork\Ui\Renderer;

use Plainwork\Ui\Component\InlineList;
use Plainwork\Ui\Component\HtmlElement;

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

        $spacing = $el->getSpacing();
        $heroIndex = $el->getHeroIndex();

        $ret = (null === $heroIndex) ? (new HtmlElement('span')) : (new HtmlElement('div'));
        $ret->withAttr('class', 'pw-inline-list');
        if (null !== $heroIndex) {
            $ret->withAttr('class', 'pw-inline-list--with-hero');
        }

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

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

        if ($el->isCommaSeparated()) {
            $ret->withAttr('class', 'pw-comma-separated');
        }

        $i_ = 0;
        foreach ($items as $item) {
            if ($el->isMiddotSeparated()) {
                if ($i_) {
                    // $v = (new HtmlElement('i'))->append('&middot;');
                    $v = '&middot;';
                    $ret->append($v);
                }
            }

            if (null === $heroIndex){
                $v = new HtmlElement('span', $item);
            } else {
                $v = new HtmlElement('div', $item);
                if ($i_ == $heroIndex) {
                    $v->withAttr('class', 'pw-inline-hero');
                }
            }

            $ret->append($v);

            ++$i_;
        }

        return $ret;
    }
}
