<?php
/**
 * Copyright since 2025 InPost S.A.
 *
 * For the full license information, please view the LICENSE file bundled with the module.
 *
 * @author InPost S.A.
 * @copyright since 2025 InPost S.A.
 * @license MIT
 */

declare(strict_types=1);

namespace InPost\International\Form\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;

if (!defined('_PS_VERSION_')) {
    exit;
}

/**
 * Sets the event data to the initial data if the form was not submitted.
 */
final class UseInitialDataListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            FormEvents::PRE_SUBMIT => 'preSubmit',
        ];
    }

    public function preSubmit(FormEvent $event): void
    {
        if (null !== $event->getData()) {
            return;
        }

        $form = $event->getForm();

        if (0 === count($form)) {
            $event->setData($form->getViewData());
        } else {
            $event->setData(array_map(static function (FormInterface $form) {
                return $form->getViewData();
            }, $form->all()));
        }
    }
}
