<?php declare(strict_types=1);

namespace Newland\ToubizWidgetRendering\Utility;

use function Safe\json_encode;

class HtmlUtility
{

    public function build(string $tagName, array $attributes = [], array $content = []): string
    {
        $attributeString = '';
        foreach ($attributes as $name => $value) {
            $value = str_replace('"', '&quot;', $value);
            $attributeString .= sprintf(' %s="%s"', $name, $value);
        }

        return sprintf(
            '<%1$s%2$s>%3$s</%1$s>',
            $tagName,
            $attributeString,
            $this->siblings($content)
        );
    }

    public function buildVue(string $tagName, array $attributes = [], array $content = []): string
    {
        $vueAttributes = [];
        foreach ($attributes as $name => $value) {
            $flags = JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT;
            $vueAttributes[':' . $name] = json_encode($value, $flags);
        }
        return $this->build($tagName, $vueAttributes, $content);
    }

    public function siblings(array $siblings): string
    {
        return implode("\n", $siblings);
    }
}
