<?php

namespace Lc\SovBundle\Component;

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\Validator\Constraints\EqualTo;
use Symfony\Component\Validator\Constraints\NotNull;

class FormComponent
{
    protected ParameterBagInterface $parameterBag;

    public function __construct(ParameterBagInterface $parameterBag)
    {
        $this->parameterBag = $parameterBag;
    }

    public function addCaptchaType(FormBuilderInterface $builder)
    {
        $builder->add('specialField', HiddenType::class, [
                'data' => 0,
                'mapped' => false,
                'attr' => [
                        'class' => 'special-field'
                ],
                'constraints' => [
                        new NotNull(),
                        new EqualTo(['value' => $this->parameterBag->get('app.captcha_value'), 'message' => 'Valeur incorrecte'])
                ],
        ]);
    }

    // uploadImageTicketMessage
    public function uploadFile($form, $child, $directory, $subdirectory): ?string
    {
        $file = $form->get($child)->getData();

        if ($file) {
            $originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
            $newFilename = uniqid().'.'.$file->guessExtension();

            try {
                $file->move(
                        $directory,
                        $newFilename
                );
            } catch (FileException $e) {
                throw new \ErrorException("Une erreur est survenue lors de l'upload du fichier.");
            }

            return $subdirectory.$newFilename;
        }

        return false;
    }

}
