<?php

namespace AutoAdmin\Bundle\Admin\Form\TypeGuesser;

use AutoAdmin\Bundle\Admin\Attribute\Loader\AttributeLoader;
use Doctrine\ORM\Mapping\Column;

abstract class AbstractAdminTypeGuesser implements AdminTypeGuesserInterface
{
    protected AttributeLoader $attributeLoader;

    public function setAttributeLoader(AttributeLoader $attributeLoader)
    {
        $this->attributeLoader = $attributeLoader;
    }

    public function supportStringType(array $propertyConfig): bool
    {
        $type = $propertyConfig['type'] ?? null;

        return in_array($type, $this->getMatchingConfigStrings());
    }

    public function supportPropertyType(string $class, string $property): bool
    {;
        if ($this->supportAttributes($class, $property)) {
            return true;
        }

        $reflectionClass = new \ReflectionClass($class);
        $reflectionProperty = $reflectionClass->getProperty($property);
        $reflectionPropertyType = $reflectionProperty->getType();

        if ($reflectionPropertyType && in_array($reflectionPropertyType->getName(), $this->getMatchingPropertyTypes())) {
            return true;
        }

        return false;
    }

    public function supportAttributes(string $class, string $property): bool
    {
        $classAttributes = $this->attributeLoader->load($class);
        $propertyAttributes = $classAttributes->getAttributesByProperty($property);

        if (
            $propertyAttributes->hasAttribute(Column::class)
            && ($attribute = $propertyAttributes->getAttribute(Column::class))
            && !empty($attribute['type'])
            && in_array($attribute['type'], $this->getMatchingAttributes())
        ) {
            return true;
        }

        return false;
    }
}
