<?php
/**
 * Select type handler
 *
 * @author Elze Kool <info@visualmedia.nl>
 */

namespace VisualM\FormBundle\Form\TypeHandler;

use Symfony\Component\Validator\Constraints as Assert;
use VisualM\FormBundle\Entity\FormFieldInterface;

/**
 * Select type handler
 *
 * @author Elze Kool <info@visualmedia.nl>
 */
class SelectTypeHandler extends AbstractChoiceTypeHandler
{
    /**
     * {@inheritdoc}
     */
    public function getOptions(FormFieldInterface $formField)
    {
        $choices = $this->createChoices($formField->getWaarden());
        $options = [
            'required' => $formField->getVerplicht(),
            'constraints' => [new Assert\Choice(array('choices' => array_values($choices)))],
            'choices' => $choices,
        ];

        if ($formField->getRegex() != '' AND $formField->getRegex() != null) {
            $options['constraints'][] = new Assert\Regex([ 'pattern' => $formField->getRegex()]);
        }
        if ($formField->getVerplicht()) {
            $options['constraints'][] = new Assert\NotBlank();
        } else {
            $this->addEmptyDataOptions($options);
        }
        return $options;
    }

    /**
     * {@inheritdoc}
     */
    public function normalizeValue(FormFieldInterface $formField, $value)
    {
        return $value;
    }

    protected function addEmptyDataOptions(&$options)
    {
        $options['placeholder'] = '';
        $options['empty_data'] = null;
    }

    public function completeOptionChoices(&$options, $data)
    {
        if ($data === null) {
            $this->addEmptyDataOptions($options);
        } else {
            parent::completeOptionChoices($options, $data);
        }
    }

    }

