<?php


namespace AutoAdmin\Bundle\BrickBuilder\Html;


class AttributeMap
{
    protected array $attributes = [];

    public function __construct(array $attributes = [])
    {
        $this->attributes = $attributes;
    }

    public function get(string $attribute)
    {
        return $this->attributes[$attribute];
    }

    public function set(string $attribute, string $value, bool $specialChars = true): void
    {
        $this->attributes[$attribute] = $specialChars ? htmlspecialchars($value) : $value;
    }

    public function delete(string $attribute): void
    {
        unset($this->attributes[$attribute]);
    }

    public function addClass(string $class): self
    {
        if (!$this->hasClass($class)) {
            if (!empty($this->attributes['class'])) {
                $this->attributes['class'] .= ' ' . $class;
            } else {
                $this->attributes['class'] = $class;
            }
        }

        return $this;
    }

    public function hasClass(string $attribute): bool
    {
        return $this->has('class')
            && in_array($attribute, array_filter(explode(' ', $this->attributes['class'] ?? '')));
    }

    public function has(string $attribute): bool
    {
        return isset($this->attributes[$attribute]);
    }

    public function removeClass(string $class)
    {
        if ($this->hasClass($class)) {
            $classes = $this->attributes['class'] ?? '';
            $classes = str_replace($class, '', $classes);
            $classes = preg_replace('/\ +/', ' ', $classes);

            $this->attributes['class'] = trim($classes);
        }

        return $this;
    }

    public function load(array $attributes): void
    {
        $this->attributes = $attributes;
    }

    public function parse(string $attributeString): void
    {
        preg_match_all(
            '/(\ +)?(?<attr_name>[a-z0-9-]+)(="(?<attr_value>[^"]*?)")?(\ +)?/s',
            $attributeString,
            $matchedAttributes
        );

        $attr = [];
        if ($matchedAttributes[0]) {
            $matched = $matchedAttributes[0];

            foreach ($matched as $matchIdx => $matchedAttribute) {
                $name = $matchedAttributes['attr_name'][$matchIdx];
                $value = $matchedAttributes['attr_value'][$matchIdx];
                $attr[$name] = $value;
            }
        }

        $this->attributes = $attr;
    }

    public function compile(): string
    {
        return ' ' . implode(
                ' ',
                array_map(
                    function ($key, $value) {
                        $value = htmlspecialchars($value);
                        return $key . '="' . $value . '"';
                    },
                    array_keys($this->attributes),
                    $this->attributes
                )
            );
    }

    public function toArray(): array
    {
        return $this->attributes;
    }
}
