<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\CoreBundle\Shared\Form\Type\ValueObject;

use Serenity\CoreBundle\Shared\ValueObject\AddressEmail;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\DataMapperInterface;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class AddressEmailType extends AbstractType implements DataMapperInterface
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder->add('email', EmailType::class, [
            'label' => 'Email',
            'required' => true,
        ]);
        $builder->add('name', TextType::class, [
            'label' => 'Nom à afficher avec l\'email',
            'required' => true,
        ]);
        $builder->setDataMapper($this);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults(
            [
                'class' => AddressEmail::class,
                'empty_data' => null,
            ]
        );
    }

    public function mapDataToForms(mixed $viewData, \Traversable $forms): void
    {
        if (null === $viewData) {
            return;
        }

        $forms = iterator_to_array($forms);
        $forms['email']->setData($viewData->email);
        $forms['name']->setData($viewData->name);
    }

    public function mapFormsToData(\Traversable $forms, mixed &$viewData): void
    {
        $formFields = iterator_to_array($forms);
        $viewData = new AddressEmail($formFields['email']->getData(), $formFields['name']->getData());
    }
}
