<?php

namespace AutoAdmin\Bundle\Admin\Form\TypeGuesser\Guesser\Relation;

use AutoAdmin\Bundle\Admin\Form\Type\Component\RichEntityType;
use AutoAdmin\Bundle\Admin\Form\TypeGuesser\AbstractAdminTypeGuesser;

abstract class AbstractAdminRelationTypeGuesser extends AbstractAdminTypeGuesser
{
    private string $targetEntity = '';

    abstract public function getRelationType(): string;
    abstract public function getDefaultRelationFormTypeOptions(): array;

    public function setTargetEntity(string $targetEntity)
    {
        $this->targetEntity = $targetEntity;
    }

    public function getTargetEntity(): string
    {
        return $this->targetEntity;
    }

    public function getFormType(): string
    {
        return RichEntityType::class;
    }

    public function getDefaultFormTypeOptions(): array
    {
        return array_merge(
            [
                'class' => $this->getTargetEntity(),
            ],
            $this->getDefaultRelationFormTypeOptions(),
        );
    }

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

        if (
            $propertyAttributes->hasAttribute($this->getRelationType())
            && ($attribute = $propertyAttributes->getAttribute($this->getRelationType()))
            && !empty($attribute['targetEntity'])
        ) {
            $this->setTargetEntity($attribute['targetEntity']);

            return true;
        }

        return false;
    }

    /*
     * Return an empty array because this method is not used by RelationGuesser
     */
    public function getMatchingAttributes(): array
    {
        return [];
    }
}
