<?php

namespace App\Form\Type;

use App\Entity\Geoloc;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ButtonType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
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, array(
                'label' => 'Adresse :',
                'required' => $options['required']
            ))
            ->add('cpostal', TextType::class, array(
                'label' => 'Code postal :',
                'required' => $options['required']
            ))
            ->add('ville', TextType::class, array(
                'label' => 'Ville :',
                'required' => $options['required']
            ))
        ;
        if ($options['with_geoloc'] === true) {
            $builder
                ->add('search', ButtonType::class, [
                    'label' => 'Géolocaliser',
                    'attr' => ['class' => 'searchLatLon btn btn-primary', 'data-url' => $this->router->generate('geolocAdresse')],
                ])
            ;
        }
        if ($options['with_latlon'] === true || (!empty($geoloc) && (!empty($geoloc->getLat()) || !empty($geoloc->getLon())))) {
            $builder
                ->add('lat', null, array(
                    'label' => 'Latitude :',
                    'required' => false
                ))
                ->add('lon', null, array(
                    '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';
    }
}
