<?php

namespace Lc\SovBundle\Form\Common;


use EasyCorp\Bundle\EasyAdminBundle\Form\Type\EaFormPanelType;
use Symfony\Bridge\Doctrine\Form\DoctrineOrmTypeGuesser;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Custom form type that deals with some of the logic used to render the
 * forms used to create and edit EasyAdmin entities.
 *
 * @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
 */
class CrudFormType extends AbstractType
{

    protected $parent;
    protected $doctrineOrmTypeGuesser;

    public function __construct(
            DoctrineOrmTypeGuesser $doctrineOrmTypeGuesser,
            \EasyCorp\Bundle\EasyAdminBundle\Form\Type\CrudFormType $crudFormType
    ) {

        $this->parent = $crudFormType;
        $this->doctrineOrmTypeGuesser = $doctrineOrmTypeGuesser;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $this->parent->buildForm($builder, $options);
        $entityDto = $options['entityDto'];
        $formPanels = [];
        $currentFormPanel = 0;
        foreach ($entityDto->getFields() as $fieldDto) {

            if (null === $formFieldType = $fieldDto->getFormType()) {
                $guessType = $this->doctrineOrmTypeGuesser->guessType($entityDto->getFqcn(), $fieldDto->getProperty());
                $formFieldType = $guessType->getType();
                $formFieldOptions = array_merge($guessType->getOptions(), $formFieldOptions);
            }

            if (EaFormPanelType::class === $formFieldType) {
                ++$currentFormPanel;
                $formPanels[$currentFormPanel] = [
                        'form_tab' => $currentFormTab ?? null,
                        'label' => $fieldDto->getLabel(),
                        'help' => $fieldDto->getHelp(),
                        'css_class' => $fieldDto->getCssClass(),
                ];
                foreach ($fieldDto->getCustomOptions()->all() as $customOptionKey => $customOption) {
                    $formPanels[$currentFormPanel][$customOptionKey] = $customOption;
                }
                continue;
            }
        }
        $builder->setAttribute('ea_form_panels', $formPanels);
        //$this->niche->buildForm($builder, $options);
    }

    public function finishView(FormView $view, FormInterface $form, array $options)
    {
        $this->parent->finishView($view, $form, $options);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $this->parent->configureOptions($resolver);
    }

    public function getBlockPrefix()
    {
        return $this->parent->getBlockPrefix();
    }


}
