<?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\ReportBundle\Tests\Controller;

use Chill\CustomFieldsBundle\Entity\CustomFieldsGroup;
use Chill\PersonBundle\Entity\Person;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\DomCrawler\Form;
use Symfony\Component\DomCrawler\Link;

/**
 * Test the life cycles of controllers, according to
 * https://redmine.champs-libres.coop/projects/report/wiki/Test_plan_for_report_lifecycle.
 *
 * @internal
 *
 * @coversNothing
 */
final class ReportControllerTest extends WebTestCase
{
    public const REPORT_NAME_FIELD = 'cFGroup';

    /**
     * @var \SClientymfony\Component\BrowserKit\
     */
    private static $client;

    private static ?object $em = null;

    /**
     * @var CustomFieldsGroup
     */
    private static $group;

    /**
     * @var Person
     */
    private static $person;

    private static $user;

    public static function setUpBeforeClass(): void
    {
        self::bootKernel();

        self::$em = self::$kernel->getContainer()
            ->get('doctrine.orm.entity_manager');

        // get a random person
        self::$person = self::$kernel->getContainer()
            ->get('doctrine.orm.entity_manager')
            ->getRepository(Person::class)
            ->findOneBy(
                [
                    'lastName' => 'Charline',
                    'firstName' => 'Depardieu',
                ]
            );

        if (null === self::$person) {
            throw new \RuntimeException('The expected person is not present in the database. Did you run `php app/console doctrine:fixture:load` before launching tests ? '."(expecting person is 'Charline Depardieu'");
        }

        $customFieldsGroups = self::$kernel->getContainer()
            ->get('doctrine.orm.entity_manager')
            ->getRepository(CustomFieldsGroup::class)
            ->findBy(['entity' => \Chill\ReportBundle\Entity\Report::class]);
        // filter customFieldsGroup to get only "situation de logement"
        $filteredCustomFieldsGroupHouse = array_filter(
            $customFieldsGroups,
            static fn (CustomFieldsGroup $group) => \in_array('Situation de logement', $group->getName(), true)
        );
        self::$group = $filteredCustomFieldsGroupHouse[0];

        self::$user = self::$kernel->getContainer()
            ->get('doctrine.orm.entity_manager')
            ->getRepository(\Chill\MainBundle\Entity\User::class)
            ->findOneBy(['username' => 'center a_social']);
    }

    protected function setUp(): void
    {
        self::$client = self::createClient([], [
            'PHP_AUTH_USER' => 'center a_social',
            'PHP_AUTH_PW' => 'password',
        ]);
    }

    /**
     * @param type $username
     *
     * @return Client
     */
    public function getAuthenticatedClient($username = 'center a_social')
    {
        return self::createClient([], [
            'PHP_AUTH_USER' => $username,
            'PHP_AUTH_PW' => 'password',
        ]);
    }

    /**
     * @return type
     *
     * @depends testMenu
     */
    public function testChooseReportModelPage(Link $link)
    {
        // When I click on "add a report" link in menu
        $client = $this->getAuthenticatedClient();
        $crawlerAddAReportPage = $client->click($link);

        $form = $crawlerAddAReportPage->selectButton('Créer un nouveau rapport')->form();

        $this->assertInstanceOf(
            Form::class,
            $form,
            'I can see a form with a button "add a new report" '
        );

        $this->assertGreaterThan(
            1,
            \count($form->get(self::REPORT_NAME_FIELD)
                ->availableOptionValues()),
            'I can choose between report models'
        );

        $possibleOptionsValue = $form->get(self::REPORT_NAME_FIELD)
            ->availableOptionValues();
        $form->get(self::REPORT_NAME_FIELD)->setValue(
            $possibleOptionsValue[array_rand($possibleOptionsValue)]
        );

        $client->submit($form);

        $this->assertTrue($client->getResponse()->isRedirect());

        return $client->followRedirect();
    }

    /**
     * Test that setting a Null date redirect to an error page.
     *
     * @depends testNewReportPage
     */
    public function testInvalidDate(Form $form): never
    {
        $client = $this->getAuthenticatedClient();
        $this->markTestSkipped('This test raise an error since symfony 2.7. '
                .'The user is not correctly reloaded from database.');
        $filledForm = $this->fillCorrectForm($form);
        $filledForm->get('chill_reportbundle_report[date]')->setValue('invalid date value');

        $crawler = $client->submit($filledForm);

        $this->assertFalse($client->getResponse()->isRedirect());
        $this->assertGreaterThan(0, $crawler->filter('.error')->count());
    }

    /**
     * Test that a incorrect value in user will show an error page.
     *
     * @depends testNewReportPage
     */
    public function testInvalidUser(Form $form)
    {
        $client = $this->getAuthenticatedClient();
        $filledForm = $this->fillCorrectForm($form);
        $select = $filledForm->get('chill_reportbundle_report[user]')
            ->disableValidation()
            ->setValue(-1);

        $crawler = $client->submit($filledForm);

        $this->assertFalse($client->getResponse()->isRedirect());
        $this->assertGreaterThan(0, $crawler->filter('.error')->count());
    }

    /**
     * @depends testValidCreate
     *
     * @param int $reportId
     */
    public function testList($reportId)
    {
        $client = $this->getAuthenticatedClient();
        $crawler = $client->request('GET', sprintf(
            '/fr/person/%s/report/list',
            self::$person->getId()
        ));

        $this->assertTrue($client->getResponse()->isSuccessful());

        $linkSee = $crawler->filter('.bt-view')->links();
        $this->assertGreaterThan(0, \count($linkSee));
        $this->assertMatchesRegularExpression(sprintf(
            '|/fr/person/%s/report/[0-9]*/view$|',
            self::$person->getId(),
            $reportId
        ), $linkSee[0]->getUri());

        $linkUpdate = $crawler->filter('.bt-update')->links();
        $this->assertGreaterThan(0, \count($linkUpdate));
        $this->assertMatchesRegularExpression(sprintf(
            '|/fr/person/%s/report/[0-9]*/edit$|',
            self::$person->getId(),
            $reportId
        ), $linkUpdate[0]->getUri());
    }

    /**
     * Set up the browser to be at a random person general page (/fr/person/%d/general),
     * check if there is a menu link for adding a new report and return this link (as producer).
     *
     * We assume that :
     * - we are on a "person" page
     * - there are more than one report model
     */
    public function testMenu()
    {
        $client = $this->getAuthenticatedClient();
        $crawlerPersonPage = $client->request('GET', sprintf(
            '/fr/person/%d/general',
            self::$person->getId()
        ));

        if (!$client->getResponse()->isSuccessful()) {
            var_dump($crawlerPersonPage->html());

            throw new \RuntimeException('the request at person page failed');
        }

        $link = $crawlerPersonPage->selectLink("AJOUT D'UN RAPPORT")->link();
        $this->assertInstanceOf(
            Link::class,
            $link,
            'There is a "add a report" link in menu'
        );
        $this->assertStringContainsString(
            sprintf(
                '/fr/person/%d/report/select/type/for/creation',
                self::$person->getId()
            ),
            $link->getUri(),
            'There is a "add a report" link in menu'
        );

        return $link;
    }

    /**
     * @return type
     *
     * @depends testChooseReportModelPage
     */
    public function testNewReportPage(Crawler $crawlerNewReportPage)
    {
        $addForm = $crawlerNewReportPage
            ->selectButton('Ajouter le rapport')
            ->form();

        $this->assertInstanceOf(
            Form::class,
            $addForm,
            'I have a report form'
        );

        $this->isFormAsExpected($addForm);

        return $addForm;
    }

    /**
     * Test that setting a Null date redirect to an error page.
     */
    public function testNullDate()
    {
        $client = $this->getAuthenticatedClient();
        $form = $this->getReportForm(
            self::$person,
            self::$group,
            $client
        );
        // var_dump($form);
        $filledForm = $this->fillCorrectForm($form);
        $filledForm->get('chill_reportbundle_report[date]')->setValue('');
        // $this->markTestSkipped();
        $crawler = $this->getAuthenticatedClient('center a_administrative')->submit($filledForm);

        $this->assertFalse($client->getResponse()->isRedirect());
        $this->assertGreaterThan(0, $crawler->filter('.error')->count());
    }

    /**
     * test the update form.
     *
     * @depends testValidCreate
     *
     * @param int $reportId
     */
    public function testUpdate($reportId)
    {
        $client = $this->getAuthenticatedClient();
        $crawler = $client->request(
            'GET',
            sprintf('/fr/person/%s/report/%s/edit', self::$person->getId(), $reportId)
        );

        $this->assertTrue($client->getResponse()->isSuccessful());

        $form = $crawler
            ->selectButton('Enregistrer le rapport')
            ->form();

        $form->get('chill_reportbundle_report[date]')->setValue(
            (new \DateTime('yesterday'))->format('d-m-Y')
        );

        $client->submit($form);

        $this->assertTrue($client->getResponse()->isRedirect(
            sprintf(
                '/fr/person/%s/report/%s/view',
                self::$person->getId(),
                $reportId
            )
        ));

        $this->assertEquals(new \DateTime('yesterday'), self::$kernel->getContainer()
            ->get('doctrine.orm.entity_manager')
            ->getRepository('ChillReportBundle:Report')
            ->find($reportId)
            ->getDate());
    }

    /**
     * Test the creation of a report.
     *
     * depends testNewReportPage
     * param Form $form
     */
    public function testValidCreate()
    {
        $client = $this->getAuthenticatedClient();
        // $this->markTestSkipped("This test raise an error since symfony 2.7. "
        //        . "The user is not correctly reloaded from database.");
        $addForm = $this->getReportForm(self::$person, self::$group, $client);
        $filledForm = $this->fillCorrectForm($addForm);
        $c = $client->submit($filledForm);

        $this->assertTrue(
            $client->getResponse()->isRedirect(),
            "The next page is a redirection to the new report's view page"
        );
        $client->followRedirect();

        $this->assertMatchesRegularExpression(
            '|/fr/person/'.self::$person->getId().'/report/[0-9]*/view$|',
            $client->getHistory()->current()->getUri(),
            "The next page is a redirection to the new report's view page"
        );

        $matches = [];
        preg_match(
            '|/report/([0-9]*)/view$|',
            (string) $client->getHistory()->current()->getUri(),
            $matches
        );

        return $matches[1];
    }

    /**
     * Test the view of a report.
     *
     * @depends testValidCreate
     *
     * @param int $reportId
     */
    public function testView($reportId)
    {
        $client = $this->getAuthenticatedClient();
        $client->request(
            'GET',
            sprintf('/fr/person/%s/report/%s/view', self::$person->getId(), $reportId)
        );

        $this->assertTrue(
            $client->getResponse()->isSuccessful(),
            'the page is shown'
        );
    }

    /**
     * get a form for report new.
     *
     * @param \Chill\ReportBundle\Tests\Controller\Person $person
     *
     * @return Form
     */
    protected function getReportForm(
        Person $person,
        CustomFieldsGroup $group,
        \Symfony\Component\BrowserKit\AbstractBrowser $client,
    ) {
        $url = sprintf(
            'fr/person/%d/report/cfgroup/%d/new',
            $person->getId(),
            $group->getId()
        );
        $crawler = $client->request('GET', $url);

        return $crawler->selectButton('Ajouter le rapport')
            ->form();
    }

    /**
     * fill the form with correct data.
     */
    private function fillCorrectForm(Form $form)
    {
        $form->get('chill_reportbundle_report[date]')->setValue(
            (new \DateTime())->format('d-m-Y')
        );

        return $form;
    }

    /**
     * Test the expected field are present.
     *
     * @param bool $isDefault if the form should be at default values
     */
    private function isFormAsExpected(Form $form, $isDefault = true)
    {
        $this->assertTrue(
            $form->has('chill_reportbundle_report[date]'),
            'the report form have a field "date"'
        );
        $this->assertTrue(
            $form->has('chill_reportbundle_report[user]'),
            'the report form have field "user" '
        );

        $this->assertEquals('select', $form->get('chill_reportbundle_report[user]')
            ->getType(), 'the user field is a select input');

        if ($isDefault) {
            $date = new \DateTime('now');
            $this->assertEquals(
                $date->format('d-m-Y'),
                $form->get('chill_reportbundle_report[date]')->getValue(),
                'the date field contains the current date by default'
            );

            // resolve the user
            $userId = $form->get('chill_reportbundle_report[user]')->getValue();

            $this->assertEquals(
                'center a_social',
                self::$user->getUsername(),
                'the user field is the current user by default'
            );
        }
    }
}
