<?php

namespace App\Dto\Ag;

use App\Entity\Ag\Main;
use App\Entity\Ag\MainMember;
use App\Entity\Members;
use App\Repository\MembersRepository;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class AgMembersType extends AbstractType
{
    public function __construct(private MembersRepository $membersRepository)
    {
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        /** @var Main $main */
        $main = $options['data']->getMain();
        $choices = [];

        foreach ($this->membersRepository->findAll() as $member) {
            if(!is_null($main)) {
                $present = $main->getMainMembers()->filter(function (MainMember $mainMember) use ($member) {
                    return $member->getId() == $mainMember->getMember()->getId();
                })->first();
                if (!$present instanceof MainMember) {
                    $choices[$member->getPseudo()] = $member->getId();
                }
            }
        }

        $builder
            ->add('member', ChoiceType::class, [
                'label' => 'Membre',
                'choices' => $choices,
                'mapped' => false,
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefault('data_class',MainMember::class);
    }
}
