<?php
/**
 * Text type handler
 *
 * @author Elze Kool <info@visualmedia.nl>
 */
namespace VisualM\FormBundle\Form\TypeHandler;

use \DateTime;

use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\DependencyInjection\ContainerBuilder;

use VisualM\FormBundle\Entity\FormField;
use VisualM\FormBundle\Entity\FormFieldInterface;

/**
 * Text type handler
 *
 * @author Elze Kool <info@visualmedia.nl>
 */
class FileTypeHandler implements FormTypeHandlerInterface
{
    /**
     * Container
     * @param mixed $container
     */
    protected $container;

    /**
     * Constructor
     *
     * @param mixed $container
     */
    public function __construct($container)
    {
        $this->container = $container;
    }

    /**
     * {@inheritdoc}
     */
    public function getSymfonyType(FormFieldInterface $formField)
    {
        return FileType::class;
    }

    /**
     * {@inheritdoc}
     */
    public function getOptions(FormFieldInterface $formField)
    {
        $constraints = [
            new Assert\File([
                'maxSize' => $this->container->getParameter('visualm.form.file_max_size'),
                'mimeTypes' => $this->container->getParameter('visualm.form.file_types'),
            ])

        ];

        return [
            'required' => $formField->getVerplicht(),
            'constraints' => $constraints
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function normalizeValue(FormFieldInterface $formField, $value)
    {
        $datenow = new DateTime();

        if (!empty($value)){
            preg_match('/(.*?)([\/.].*)/'  ,$value->getClientOriginalName(), $match);
            $filename = $match[1];
            $extention = $match[2];
            $newfilename = $filename . '-' . $datenow->format('d-m-Y') . $extention;

            return $newfilename;
        }
    }
}
