<?php
/**
 * MetaTag FormType
 *
 * @author Elze Kool <info@visualmedia.nl>
 */

namespace VisualM\TagManagerBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use VisualM\TagManagerBundle\Doctrine\FieldType\WijzigbaarType;
use VisualM\TagManagerBundle\Entity\MetaTag;

/**
 * MetaTag FormType
 *
 * @author Elze Kool <info@visualmedia.nl>
 */
class MetaTagType extends AbstractType
{
    /**
     * Authorization Checker
     * @var AuthorizationCheckerInterface
     */
    protected $authChecker;

    /**
     * Constructor
     *
     * @param AuthorizationCheckerInterface $authChecker Authorization Checker
     */
    public function __construct(AuthorizationCheckerInterface $authChecker)
    {
        $this->authChecker = $authChecker;
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // Becouse we can dynamicly add metaTags we need the preset field as hidden
        // field. It contains the id of the corresponding set
        $builder->add('metaTagPreset', EntityHiddenType::class, [
            'class' => 'VisualM\TagManagerBundle\Entity\MetaTagPreset'
        ]);

        $builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) {
            $form = $event->getForm();
            $data = $event->getData();

            // Check if we should allow editing of the inhoud field
            if ($data === null ||
                $data->getMetaTagPreset()->getInhoudWijzigbaar() === WijzigbaarType::VOLLEDIG ||
                ($this->authChecker->isGranted('ROLE_PERM_META_TAG_BEPERKT') && $data->getMetaTagPreset()->getInhoudWijzigbaar() === WijzigbaarType::BEPERKT)
            ) {
                $form->add('inhoud', TextareaType::class, array(
                    'label' => 'meta_tag.inhoud',
                    'attr' => [ 'rows' => 6, 'cols' => 100 ],
                    'required' => $data != null ? $data->getMetaTagPreset()->getRequired() : true,
                ));
                $form->add('inhoudIsExpression', CheckboxType::class, array(
                    'label' => 'meta_tag.inhoud_is_expression',
                    'required' => false,
                ));
            }

            // Check if we should allow editing of the zichtbaar field
            if (($data === null) ||
                $data->getMetaTagPreset()->getZichtbaarWijzigbaar() === WijzigbaarType::VOLLEDIG ||
                ($this->authChecker->isGranted('ROLE_PERM_META_TAG_BEPERKT') && $data->getMetaTagPreset()->getZichtbaarWijzigbaar() === WijzigbaarType::BEPERKT)
            ) {
                $form->add('zichtbaar', TextareaType::class, array('label' => 'meta_tag.zichtbaar', 'attr' => [ 'rows' => 6, 'cols' => 100 ]));
                $form->add('zichtbaarIsExpression', CheckboxType::class, array(
                    'label'     => 'meta_tag.zichtbaar_is_expression',
                    'required'  => false,
                ));

                $zichtbaar_is_expression = $data === null ? false : $data->getZichtbaarIsExpression();
                $default = $zichtbaar_is_expression ? true : ($data === null ? true : ($data->getZichtbaar() == "0" ? false : true));
                $form->add('zichtbaarSelect', ChoiceType::class, array(
                    'label' => 'meta_tag.zichtbaar',
                    'choices' => array(
                        'meta_tag.zichtbaar_select.yes' => true,
                        'meta_tag.zichtbaar_select.no' => false,
                    ),
                    'choices_as_values' => true,
                    'choice_value' => function ($value) {
                        return $value ? 'true' : 'false';
                    },
                    'mapped' => false,
                    'data' => $default,
                ));
            }
        });

        $builder->addEventListener(FormEvents::POST_SUBMIT, function(FormEvent $event) {
            $form = $event->getForm();
            $data = $event->getData();

            $meta_tag_preset = $data->getMetaTagPreset();

            // Check if Zichtbaar was editable
            if (
                ($meta_tag_preset->getZichtbaarWijzigbaar() === WijzigbaarType::NIET) OR
                (!$this->authChecker->isGranted('ROLE_PERM_META_TAG_BEPERKT') AND $meta_tag_preset->getZichtbaarWijzigbaar() === WijzigbaarType::BEPERKT)
            ) {
                // If not get data from its preset
				if ($data->getId() === null) {
					$data->setZichtbaar($meta_tag_preset->getZichtbaar());
					$data->setZichtbaarIsExpression($meta_tag_preset->getZichtbaarIsExpression());
				}

            // Else check if data was an expression and handle select box
            } else if ($data->getZichtbaarIsExpression() == false) {
                $data->setZichtbaar($form->get('zichtbaarSelect')->getData() ? "1" : "0");
            }

            // Check if Inhoud was editable
            if (
                ($meta_tag_preset->getInhoudWijzigbaar() === WijzigbaarType::NIET) OR
                (!$this->authChecker->isGranted('ROLE_PERM_META_TAG_BEPERKT') AND $meta_tag_preset->getInhoudWijzigbaar() === WijzigbaarType::BEPERKT)
            ) {
                // If not get data from its preset
                $data->setInhoud($data->getMetaTagPreset()->getInhoud());
                $data->setInhoudIsExpression($data->getMetaTagPreset()->getInhoudIsExpression());
            }

            $event->setData($data);
        });
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'meta_tag';
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'VisualM\TagManagerBundle\Entity\MetaTag',
            'translation_domain' => 'forms'
        ));
    }
}
