<?php


namespace AutoAdmin\Bundle\Admin\Form\Type\Component;


use AutoAdmin\Bundle\Content\Model\CreatedAtInterface;
use AutoAdmin\Bundle\Content\Model\NameInterface;
use AutoAdmin\Bundle\Content\Model\TranslatableInterface;
use AutoAdmin\Bundle\Content\Repository\AbstractContentRepository;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;

class RichEntityType extends AbstractHelperType
{
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $this->addViewClass($view, 'aa-ft-rich-entity');
        if ($options['disable_js_sorting'] === true) {
            $this->addViewClass($view, 'aa-ft-unsorted');
        }
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        parent::configureOptions($resolver);
        $resolver->setDefault('placeholder', 'select.none');

        $resolver->setDefault('disable_js_sorting', false);

        $resolver->setDefault('choice_label', function ($item) {
            if ($item instanceof TranslatableInterface && ($tr = $item->getCurrentTranslation(
                )) instanceof NameInterface) {
                return $tr->getName();
            }

            return (string)$item;
        });

        $resolver->setDefault(
            'query_builder',
            function (EntityRepository $entityRepository) {
                /** @var EntityRepository $entityRepository */
                $refl = new \ReflectionClass($entityRepository->getClassName());
                if ($entityRepository instanceof AbstractContentRepository) {
                    $qb = $entityRepository->createContentQueryBuilder();
                } else {
                    $qb = $entityRepository->createQueryBuilder('_');
                }

                if ($refl->implementsInterface(CreatedAtInterface::class)) {
                    $qb->orderBy('_.createdAt', 'DESC');
                }

                return $qb;
            }
        );
    }

    public function getParent(): string
    {
        return EntityType::class;
    }
}