<?php

namespace App\Form\Type;

use App\Entity\Adherent;
use App\Entity\SolidoumeItem;
use App\Entity\SolidoumeParameter;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
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\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\RangeType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\Security;

class SolidoumeFormType extends AbstractType
{
    protected $em;
    protected $security;
    private $defaultMontantSlider = 0;
    private $minMontantSlider = 0;
    private $maxMontantSlider = 0;

    public function __construct(EntityManagerInterface $em, Security $security)
    {
        $this->em = $em;
        $this->security = $security;
        $this->minMontantSlider = $this->em->getRepository(SolidoumeParameter::class)->getValueOf('minimum');
        $this->defaultMontantSlider = $this->minMontantSlider;
        $this->maxMontantSlider = $this->em->getRepository(SolidoumeParameter::class)->getValueOf('maximum');
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if (null == $this->security->getUser() || null == $this->security->getUser()->getAdherent() || !$this->security->getUser()->isGranted('ROLE_ADHERENT')) {
            throw new \Exception('[SOLIDOUME] Opération impossible, vous n\'êtes pas connecté en tant qu\'adhérent !');
        }
        $data = isset($options['data']) ? $options['data'] : null;
        if (null == $data) {
            $adherent = $this->security->getUser()->getAdherent();
            $amount = $this->defaultMontantSlider;
        } else {
            $adherent = $data->getAdherent();
            $amount = $data->getAmount();
        }
        $rangetickValue = implode(', ', range($this->minMontantSlider, $this->maxMontantSlider, 5));
        $rangetick = range(0, 100, 100 / (count(range($this->minMontantSlider, $this->maxMontantSlider, 5)) - 1));
        $rangetickRounded = [];
        foreach ($rangetick as $k => $r) {
            $rangetickRounded[$k] = floor($r);
        }
        $rangetickRounded[count($rangetickRounded) - 1] = 100;
        $rangetickString = '[' . implode(', ', $rangetickRounded) . ']';
        $builder
            ->add('user', HiddenType::class, [
                'data_class' => null,
                'data' => $this->security->getUser(),
                'entity_class' => User::class,
                'em' => $this->em,
            ])
            ->add('adherent', HiddenType::class, [
                'data_class' => null,
                'data' => $adherent,
                'entity_class' => Adherent::class,
                'em' => $this->em,
            ])
            ->add('amount', RangeType::class, [
                'attr' => [
                    'min' => $this->minMontantSlider,
                    'max' => $this->maxMontantSlider,
                    'data-provide' => 'slider',
                    'data-slider-ticks' => '[' . $rangetickValue . ']',
                    'data-slider-ticks-labels' => '[' . $rangetickValue . ']',
                    'data-slider-ticks-positions' => $rangetickString,
                    'data-slider-min' => $this->minMontantSlider,
                    'data-slider-max' => $this->maxMontantSlider,
                    'data-slider-step' => '5',
                    'data-slider-value' => $amount,
                    'style' => 'width:100%;',
                    'class' => 'solidoume-montant-slider',
                ],
                'label' => 'Montant : ',
                'required' => false,
            ])
            ->add('isRecurrent', CheckboxType::class, [
                'required' => false,
                'label' => 'Paiement récurrent tous les mois ?',
            ])
            ->add('paiementDate', ChoiceType::class, [
                'label' => 'Date de prélèvement',
                'required' => false,
                'choices' => range(1, 28),
                'choice_label' => function ($choice) {
                    return $choice;
                },
                'row_attr' => ['style' => 'display:none', 'class' => 'paiementDate'],
                'attr' => ['class' => 'w-50 m-auto'],
            ])
            ->add('isDonation', CheckboxType::class, [
                'required' => false,
                'label' => 'Je ne souhaite pas recevoir de contrepartie',
            ])
            ->add('save', SubmitType::class, ['label' => 'Valider'])
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => SolidoumeItem::class,
            'cascade_validation' => true,
        ]);
    }

    public function getBlockPrefix()
    {
        return 'formSolidoumeItem';
    }
}
