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

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class AsyncUploaderType extends AbstractType
{
    private readonly int $expires_delay;
    private readonly int $max_submit_delay;
    private readonly int $max_post_file_size;

    public function __construct(
        private readonly UrlGeneratorInterface $url_generator,
        ParameterBagInterface $parameters,
    ) {
        $config = $parameters->get('chill_doc_store')['openstack']['temp_url'];

        $this->expires_delay = $config['max_expires_delay'];
        $this->max_submit_delay = $config['max_submit_delay'];
        $this->max_post_file_size = $config['max_post_file_size'];
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'expires_delay' => $this->expires_delay,
            'max_post_size' => $this->max_post_file_size,
            'submit_delay'  => $this->max_submit_delay,
            'max_files' => 1,
            'error_bubbling' => false,
        ]);

        $resolver->setAllowedTypes('expires_delay', ['int']);
        $resolver->setAllowedTypes('max_post_size', ['int']);
        $resolver->setAllowedTypes('max_files', ['int']);
        $resolver->setAllowedTypes('submit_delay', ['int']);
    }

    public function buildView(
        FormView $view,
        FormInterface $form,
        array $options,
    ) {
        $view->vars['attr']['data-async-file-upload'] = true;
        $view->vars['attr']['data-generate-temp-url-post'] = $this
            ->url_generator->generate('async_upload.generate_url', [
                'expires_delay' => $options['expires_delay'],
                'method' => 'post',
                'submit_delay' => $options['submit_delay'],
            ]);
        $view->vars['attr']['data-temp-url-get'] = $this->url_generator
            ->generate('async_upload.generate_url', ['method' => 'GET']);
        $view->vars['attr']['data-max-files'] = $options['max_files'];
        $view->vars['attr']['data-max-post-size'] = $options['max_post_size'];
    }

    public function getParent()
    {
        return HiddenType::class;
    }
}
