<?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\CalendarBundle\Tests\Service\DocGenerator;

use Chill\CalendarBundle\Entity\Calendar;
use Chill\CalendarBundle\Entity\CalendarDoc;
use Chill\CalendarBundle\Service\DocGenerator\CalendarContext;
use Chill\DocGeneratorBundle\Entity\DocGeneratorTemplate;
use Chill\DocGeneratorBundle\Service\Context\BaseContextData;
use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Repository\PersonRepository;
use Chill\PersonBundle\Templating\Entity\PersonRender;
use Chill\ThirdPartyBundle\Entity\ThirdParty;
use Chill\ThirdPartyBundle\Repository\ThirdPartyRepository;
use Chill\ThirdPartyBundle\Templating\Entity\ThirdPartyRender;
use Doctrine\ORM\EntityManagerInterface;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Prophecy\Exception\Prediction\FailedPredictionException;
use Prophecy\PhpUnit\ProphecyTrait;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

/**
 * @internal
 *
 * @coversNothing
 */
final class CalendarContextTest extends TestCase
{
    use ProphecyTrait;

    public function testAdminFormReverseTransform()
    {
        $expected =
            [
                'trackDatetime' => true,
                'askMainPerson' => true,
                'mainPersonLabel' => 'docgen.calendar.Destinee',
                'askThirdParty' => false,
                'thirdPartyLabel' => 'Third party',
            ];

        $this->assertEqualsCanonicalizing($expected, $this->buildCalendarContext()->adminFormReverseTransform([]));
    }

    public function testAdminFormTransform()
    {
        $expected =
            [
                'trackDatetime' => true,
                'askMainPerson' => true,
                'mainPersonLabel' => 'docgen.calendar.Destinee',
                'askThirdParty' => false,
                'thirdPartyLabel' => 'Third party',
            ];

        $this->assertEqualsCanonicalizing($expected, $this->buildCalendarContext()->adminFormTransform($expected));
    }

    public function testBuildPublicForm()
    {
        $formBuilder = $this->prophesize(FormBuilderInterface::class);
        $calendar = new Calendar();
        $calendar
            ->addProfessional($tp1 = new ThirdParty())
            ->addProfessional($tp2 = new ThirdParty())
            ->addPerson($p1 = new Person());

        // we will try once with askThirdParty = true, once with askPerson = true, and once with both
        // so, we expect the call to be twice for each method
        $formBuilder->add('thirdParty', EntityType::class, Argument::type('array'))
            ->should(static function ($calls, $object, $method) use ($tp1, $tp2) {
                if (2 !== \count($calls)) {
                    throw new FailedPredictionException(sprintf('the $builder->add should be called exactly 2, %d receivved', \count($calls)));
                }

                $opts = $calls[0]->getArguments()[2];

                if (!\array_key_exists('label', $opts)) {
                    throw new FailedPredictionException('the $builder->add should have a label key');
                }

                if ('tplabel' !== $opts['label']) {
                    throw new FailedPredictionException('third party label not expected');
                }

                if (!$opts['choices']->contains($tp1) || !$opts['choices']->contains($tp2)) {
                    throw new FailedPredictionException('third party not present');
                }
            });
        $formBuilder->add('mainPerson', EntityType::class, Argument::type('array'))
            ->should(static function ($calls, $object, $method) use ($p1) {
                if (2 !== \count($calls)) {
                    throw new FailedPredictionException(sprintf('the $builder->add should be called exactly 2, %d receivved', \count($calls)));
                }

                $opts = $calls[0]->getArguments()[2];

                if (!\array_key_exists('label', $opts)) {
                    throw new FailedPredictionException('the $builder->add should have a label key');
                }

                if ('personLabel' !== $opts['label']) {
                    throw new FailedPredictionException('person label not expected');
                }

                if (!$opts['choices']->contains($p1)) {
                    throw new FailedPredictionException('person not present');
                }
            });

        $formBuilder->add('title', TextType::class, Argument::type('array'))
            ->shouldBeCalledTimes(3);

        foreach ([
            ['askMainPerson' => true, 'mainPersonLabel' => 'personLabel', 'askThirdParty' => true, 'thirdPartyLabel' => 'tplabel'],
            ['askMainPerson' => false, 'mainPersonLabel' => 'personLabel', 'askThirdParty' => true, 'thirdPartyLabel' => 'tplabel'],
            ['askMainPerson' => true, 'mainPersonLabel' => 'personLabel', 'askThirdParty' => false, 'thirdPartyLabel' => 'tplabel'],
        ] as $options) {
            $template = new DocGeneratorTemplate();
            $template->setOptions($options);

            $this->buildCalendarContext()->buildPublicForm($formBuilder->reveal(), $template, $calendar);
        }
    }

    public function testGetData()
    {
        $calendar = (new Calendar())
            ->addPerson($p1 = new Person())
            ->addProfessional($t1 = new ThirdParty());
        $template = (new DocGeneratorTemplate())->setOptions(
            ['askMainPerson' => true, 'mainPersonLabel' => 'personLabel', 'askThirdParty' => true, 'thirdPartyLabel' => 'tplabel'],
        );
        $contextData = [
            'mainPerson' => $p1,
            'thirdParty' => $t1,
        ];

        $normalizer = $this->prophesize(NormalizerInterface::class);
        $normalizer->normalize($p1, 'docgen', Argument::type('array'))->willReturn(['person' => '1']);
        $normalizer->normalize($t1, 'docgen', Argument::type('array'))->willReturn(['tp' => '1']);
        $normalizer->normalize($calendar, 'docgen', Argument::type('array'))->willReturn(['calendar' => '1']);

        $actual = $this->buildCalendarContext(null, $normalizer->reveal())
            ->getData($template, $calendar, $contextData);

        $this->assertEqualsCanonicalizing([
            'calendar' => ['calendar' => '1'],
            'mainPerson' => ['person' => '1'],
            'thirdParty' => ['tp' => '1'],
            'base_context' => 'data',
        ], $actual);
    }

    public function testStoreGenerated()
    {
        $calendar = new Calendar();
        $storedObject = new StoredObject();
        $contextData = ['title' => 'blabla'];
        $template = (new DocGeneratorTemplate())->setOptions(['trackDatetime' => true]);

        $em = $this->prophesize(EntityManagerInterface::class);
        $em->persist(Argument::type(CalendarDoc::class))->should(
            static function ($calls, $object, $method) use ($storedObject) {
                if (1 !== \count($calls)) {
                    throw new FailedPredictionException('the persist method should be called once');
                }

                /** @var CalendarDoc $calendarDoc */
                $calendarDoc = $calls[0]->getArguments()[0];

                if ($calendarDoc->getStoredObject() !== $storedObject) {
                    throw new FailedPredictionException('the stored object is not correct');
                }

                if ('blabla' !== $calendarDoc->getStoredObject()->getTitle()) {
                    throw new FailedPredictionException('the doc title should be the one provided');
                }

                if (!$calendarDoc->isTrackDateTimeVersion()) {
                    throw new FailedPredictionException('the track date time should be true');
                }
            }
        );

        $this->buildCalendarContext($em->reveal())->storeGenerated($template, $storedObject, $calendar, $contextData);
    }

    private function buildCalendarContext(
        ?EntityManagerInterface $entityManager = null,
        ?NormalizerInterface $normalizer = null,
    ): CalendarContext {
        $baseContext = $this->prophesize(BaseContextData::class);
        $baseContext->getData(null)->willReturn(['base_context' => 'data']);

        $personRender = $this->prophesize(PersonRender::class);
        $personRender->renderString(Argument::type(Person::class), [])->willReturn('person name');

        $personRepository = $this->prophesize(PersonRepository::class);
        $personRepository->find(Argument::type('int'))->willReturn(new Person());

        $thirdPartyRender = $this->prophesize(ThirdPartyRender::class);
        $thirdPartyRender->renderString(Argument::type(ThirdParty::class), [])->willReturn('third party name');

        $thirdPartyRepository = $this->prophesize(ThirdPartyRepository::class);
        $thirdPartyRepository->find(Argument::type('int'))->willReturn(new ThirdParty());

        $translatableStringHelper = $this->prophesize(TranslatableStringHelperInterface::class);
        $translatableStringHelper->localize(Argument::type('array'))->willReturn('blabla');

        if (null === $normalizer) {
            $normalizer = $this->prophesize(NormalizerInterface::class)->reveal();
        }

        if (null === $entityManager) {
            $entityManager = $this->prophesize(EntityManagerInterface::class)->reveal();
        }

        return new CalendarContext(
            $baseContext->reveal(),
            $entityManager,
            $normalizer,
            $personRender->reveal(),
            $personRepository->reveal(),
            $thirdPartyRender->reveal(),
            $thirdPartyRepository->reveal(),
            $translatableStringHelper->reveal()
        );
    }
}
