<?php

namespace Plainwork\Ui\Renderer;

use Plainwork\Http\Request;
use Plainwork\Ui\Component\AbstractTag;
use Plainwork\Ui\Ui;
use Plainwork\Ui\Html;

final class HtmlElementRenderer
{
    public $ui = Ui::class;
    private static $noEndTag = ['input', 'br'];

    public function __invoke(AbstractTag $el, Request $request): string
    {
        $elements = [];
        foreach ($el->getChildren() as $child) {
            $elements[] = $child;
        }

        if ($el->isAlignCenter()) {
            $el->withAttr('class', 'pw-col-align-center');
        }
        if ($el->isAlignEnd()) {
            $el->withAttr('class', 'pw-col-align-end');
        }

        $attr = $el->getAttr();

        $iis = array_keys($attr);
        foreach ($iis as $ii) {
            if (is_object($attr[$ii])) {
                $attr[$ii] = $this->ui->render($attr[$ii], $request);
            }
        }

        $ret = '';

        $tag = $el->getTag();
        if (strlen($tag)) {
            $ret .= '<' . $tag;
            if ($attr) {
                $ret .= ' ' . Html::attr($attr);
            }
            $ret .= '>';
        } else {
        }

        $isDeleted = $el->isDeleted();
        if ($isDeleted) {
            $ret .= '<del>';
        }

        foreach ($elements as $child) {
            $ret .= $this->ui->render($child, $request);
        }

        if ($isDeleted) {
            $ret .= '</del>';
        }

        if (strlen($tag)) {
            if (!in_array($tag, static::$noEndTag)) {
                $ret .= '</' . $tag . '>';
            }
        }

        return $ret;
    }
}
