<?php


namespace AutoAdmin\Bundle\Seo\Renderer;


use AutoAdmin\Bundle\Seo\Model\Alternate;
use AutoAdmin\Bundle\Seo\Model\Meta;
use AutoAdmin\Bundle\Seo\Model\SeoPage;

class TagRenderer
{
    public function render(SeoPage $seoPage): string
    {
        $html = '';

        if (!empty($seoPage->getTitle())) {
            $html .= $this->createTag('title', [], $seoPage->getTitle()) . "\n";
        }

        if (!empty($metas = $seoPage->getMetas())) {
            /** @var Meta $meta */
            foreach ($metas as $meta) {
                $html .= $this->createTag(
                        'meta',
                        [
                            'name' => $meta->getName(),
                            'content' => $meta->getValue(),
                        ]
                    ) . "\n";
            }
        }

        if (!empty($canonical = $seoPage->getCanonical())) {
            $html .= $this->createTag('link', ['rel' => 'canonical', 'href' => $canonical,]) . "\n";
        }

        if (!empty($alternates = $seoPage->getAlternates())) {
            /** @var Alternate $alternate */
            foreach ($alternates as $alternate) {
                $html .= $this->createTag(
                        'link',
                        [
                            'rel' => 'alternate',
                            'hreflang' => $alternate->getHrefLang(),
                            'href' => $alternate->getHref(),
                        ]
                    ) . "\n";
            }
        }

        return $html;
    }

    private function createTag($tag, array $attributes = [], $content = null)
    {
        $template = '<%s%s/>';
        if ($content !== null) {
            $template = '<%s%s>%s</%s>';
        }

        $arguments = [];
        $arguments[] = $template;
        $arguments[] = $tag;
        $attributeString = '';
        foreach ($attributes as $key => $value) {
            $attributeString .= ' ' . $key . '=' . sprintf("\"%s\"", str_replace("\"", "\\\"", $value));
        }

        $arguments[] = $attributeString;
        if ($content !== null) {
            $arguments[] = $content;
            $arguments[] = $tag;
        }

        return call_user_func_array('sprintf', $arguments);
    }
}
