<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Form\Type\Export;

use Chill\MainBundle\Export\ExportManager;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Choose a formatter amongst the available formatters.
 */
class PickFormatterType extends AbstractType
{
    protected $exportManager;

    public function __construct(ExportManager $exportManager)
    {
        $this->exportManager = $exportManager;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $export = $this->exportManager->getExport($options['export_alias']);
        $allowedFormatters = $this->exportManager
            ->getFormattersByTypes($export->getAllowedFormattersTypes());

        // build choices
        $choices = [];

        foreach ($allowedFormatters as $alias => $formatter) {
            $choices[$formatter->getName()] = $alias;
        }

        $builder->add('alias', ChoiceType::class, [
            'choices' => $choices,
            'multiple' => false,
            'placeholder' => 'Choose a format',
        ]);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setRequired(['export_alias']);
    }
}
