<?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 VisualM\FormBundle\Entity\FormField;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
 * Text type handler
 *
 * @author Elze Kool <info@visualmedia.nl>
 */
class FileTypeHandler implements FormTypeHandlerInterface 
{    
    protected $container;
    
    public function __construct($container){
        $this->container = $container;
    }
    
    /**
     * {@inheritdoc}
     */
    public function getSymfonyType(FormField $formField)
    {
        return FileType::class;
    }

    /**
     * {@inheritdoc}
     */
    public function getOptions(FormField $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(FormField $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;
        }
    }
    
    

}

