<?php

namespace App\Form\Type;

use App\Entity\Geoloc;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ButtonType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Routing\RouterInterface;

class GeolocFormType extends AbstractType
{
    private $router;

    public function __construct(RouterInterface $router)
    {
        $this->router = $router;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $geoloc = null;
        if (!empty($options['data'])) {
            $geoloc = $options['data'];
        }
        $builder
            ->add('adresse', TextType::class, [
                'label' => 'Adresse :',
                'required' => $options['required'],
            ])
            ->add('cpostal', TextType::class, [
                'label' => 'Code postal :',
                'required' => $options['required'],
            ])
            ->add('ville', TextType::class, [
                'label' => 'Ville :',
                'required' => $options['required'],
            ])
        ;
        if (true === $options['with_geoloc']) {
            $builder
                ->add('search', ButtonType::class, [
                    'label' => 'Géolocaliser',
                    'attr' => ['class' => 'searchLatLon btn btn-primary', 'data-url' => $this->router->generate('geolocAdresse')],
                ])
            ;
        }
        if (true === $options['with_latlon'] || (!empty($geoloc) && (!empty($geoloc->getLat()) || !empty($geoloc->getLon())))) {
            $builder
                ->add('lat', null, [
                    'label' => 'Latitude :',
                    'required' => false,
                ])
                ->add('lon', null, [
                    'label' => 'Longitude :',
                    'required' => false,
                ])
            ;
        } else {
            $builder
                ->add('lat', HiddenType::class, [
                    'label' => 'Latitude :',
                    'required' => false,
                ])
                ->add('lon', HiddenType::class, [
                    'label' => 'Longitude :',
                    'required' => false,
                ])
            ;
        }
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        // $resolver->setRequired(['with_latlon']);
        $resolver->setDefaults([
            'data_class' => Geoloc::class,
            'with_geoloc' => true,
            'with_latlon' => true,
        ]);
    }

    public function getBlockPrefix()
    {
        return 'formGeoloc';
    }
}
