<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\ActivityBundle\Tests\Form\Type;

use Chill\ActivityBundle\Entity\ActivityType;
use Chill\ActivityBundle\Form\Type\TranslatableActivityType;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Form\Extension\Core\Type\FormType;

/**
 * @internal
 *
 * @coversNothing
 */
final class TranslatableActivityTypeTest extends KernelTestCase
{
    /**
     * @var \Symfony\Component\Form\FormBuilderInterface
     */
    protected $builder;

    protected function setUp(): void
    {
        self::bootKernel();

        $this->builder = self::getContainer()
            ->get('form.factory')
            ->createBuilder(FormType::class, null, [
                'csrf_protection' => false,
                'csrf_field_name' => '_token',
            ]);

        $request = new \Symfony\Component\HttpFoundation\Request();
        $request->setLocale('fr');

        $this->container->get('request_stack')
            ->push($request);
    }

    public function testForm()
    {
        $type = $this->getRandomType();
        $form = $this->builder->add('type', TranslatableActivityType::class)
            ->getForm();

        $form->submit([
            'type' => $type->getId(),
        ]);

        $this->assertTrue($form->isSynchronized());
        $this->assertInstanceOf(
            ActivityType::class,
            $form->getData()['type'],
            'The data is an instance of Chill\ActivityBundle\Entity\ActivityType'
        );
        $this->assertEquals($type->getId(), $form->getData()['type']->getId());

        // test the ordering of the types in the form
        // since 2016-11-14 the types are not alphabetically ordered, skipping
        /*$view = $form->createView();

        $this->assertGreaterThan(0, count($view['type']->vars['choices']),
                "test that there are at least one choice");

        foreach($view['type']->vars['choices'] as $choice) {
            // initialize the previous value is not set (this is the  first)
            if (!isset($previous)) {
                $previous = $choice->label;
            } else {
                $this->assertTrue($previous < $choice->label);
                $previous = $choice->label;
            }
        }*/
    }

    /**
     * @return ActivityType
     */
    protected function getRandomType(mixed $active = true)
    {
        $types = $this->container->get('doctrine.orm.entity_manager')
            ->getRepository(ActivityType::class)
            ->findBy(['active' => $active]);

        return $types[array_rand($types)];
    }
}
