<?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\Configuration\Form\Type\Checkout;

use InPost\International\Configuration\DTO\GoogleMapsGeocoderConfig;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\DataMapperInterface;
use Symfony\Component\Form\Exception\UnexpectedTypeException;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Contracts\Translation\TranslatorInterface;

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

/**
 * @TODO: refactor the masked password field into a reusable type?
 */
final class GoogleMapsGeocoderOptionsType extends AbstractType implements DataMapperInterface
{
    private const MASKED_VALUE = '*****';
    private const DOCS_URL = 'https://developers.google.com/maps/documentation/geocoding/get-api-key';

    /**
     * @var TranslatorInterface
     */
    private $translator;

    public function __construct(TranslatorInterface $translator)
    {
        $this->translator = $translator;
    }

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('apiKey', PasswordType::class, [
                'label' => $this->translator->trans('Google Maps API key', [], 'Modules.Inpostinternational.Configuration'),
                'always_empty' => false,
                'help' => strtr(htmlspecialchars($this->translator->trans('Visit {docs_link} in order to learn how to get your API key.', [], 'Modules.Inpostinternational.Configuration')), [
                    '{docs_link}' => sprintf('<a href="%s" target="_blank">%s</a>', self::DOCS_URL, htmlspecialchars($this->translator->trans('the official documentation', [], 'Modules.Inpostinternational.Configuration'))),
                ]),
                'help_html' => true,
            ])
            ->setDataMapper($this);
    }

    public function finishView(FormView $view, FormInterface $form, array $options): void
    {
        if (!$form->get('apiKey')->getData()) {
            return;
        }

        $childView = $view['apiKey'];

        if ('' === $childView->vars['value']) {
            $childView->vars['value'] = self::MASKED_VALUE;
        }
    }

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

    /**
     * @param GoogleMapsGeocoderConfig|null $viewData
     * @param iterable<FormInterface> $forms
     */
    public function mapDataToForms($viewData, $forms): void
    {
        if (null === $viewData) {
            return;
        }

        if (!$viewData instanceof GoogleMapsGeocoderConfig) {
            throw new UnexpectedTypeException($viewData, GoogleMapsGeocoderConfig::class);
        }

        if (!is_array($forms)) {
            $forms = iterator_to_array($forms);
        }

        $forms['apiKey']->setData($viewData->getApiKey());
    }

    /**
     * @param iterable<FormInterface> $forms
     * @param GoogleMapsGeocoderConfig|null $viewData
     */
    public function mapFormsToData($forms, &$viewData): void
    {
        if (null === $viewData) {
            return;
        }

        if (!$viewData instanceof GoogleMapsGeocoderConfig) {
            throw new UnexpectedTypeException($viewData, GoogleMapsGeocoderConfig::class);
        }

        if (!is_array($forms)) {
            $forms = iterator_to_array($forms);
        }

        $apiKey = $forms['apiKey']->getData();

        if (self::MASKED_VALUE === $apiKey) {
            return;
        }

        $viewData->setApiKey($apiKey);
    }
}
