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

use Serenity\AdminBundle\Form\Type\SearchType;
use Serenity\CoreBundle\Search\SearchInterface;
use Serenity\SaasBundle\DTO\TenantSearchDTO;
use Symfony\Component\Form\DataMapperInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class TenantSearchType extends SearchType implements DataMapperInterface
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        parent::buildForm($builder, array_merge($options, [
            'sorter_choices' => TenantSearchDTO::SORTER,
            'sorter_required' => false,
            'sorter' => true,
            'button_submit' => true,
            'sorter_multiple' => true,
        ]));

        $builder->setDataMapper($this);
    }

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

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

        $forms['query']->setData($viewData->getQuery());
        if (isset($forms['direction'])) {
            $forms['direction']->setData($viewData->getDirection());
        }
        if (isset($forms['sorter'])) {
            $forms['sorter']->setData($viewData->getSorter());
        }
    }

    public function mapFormsToData(\Traversable $forms, mixed &$viewData): void
    {
        $forms = iterator_to_array($forms);
        $query = $forms['query']->getData();

        if (isset($forms['direction'])) {
            $direction = $forms['direction']->getData();
        }
        if (isset($forms['sorter'])) {
            $sorter = $forms['sorter']->getData();
        }

        $viewData = new TenantSearchDTO($query, $direction ?? null, $sorter ?? null);
    }
}
