<?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\PersonBundle\DataFixtures\ORM;

use Chill\MainBundle\DataFixtures\ORM\LoadAdministrativeLocation;
use Chill\MainBundle\DataFixtures\ORM\LoadPostalCodes;
use Chill\MainBundle\DataFixtures\ORM\LoadUserJob;
use Chill\MainBundle\Entity\Address;
use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Entity\Country;
use Chill\MainBundle\Entity\Gender;
use Chill\MainBundle\Entity\GenderEnum;
use Chill\MainBundle\Entity\Location;
use Chill\MainBundle\Entity\PostalCode;
use Chill\MainBundle\Entity\Scope;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Entity\UserJob;
use Chill\MainBundle\Repository\CenterRepository;
use Chill\MainBundle\Repository\CountryRepository;
use Chill\MainBundle\Repository\GenderRepository;
use Chill\MainBundle\Repository\ScopeRepository;
use Chill\MainBundle\Repository\UserRepository;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\MaritalStatus;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Entity\SocialWork\SocialIssue;
use Chill\PersonBundle\Repository\MaritalStatusRepository;
use Chill\PersonBundle\Repository\SocialWork\SocialIssueRepository;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Persistence\ObjectManager;
use Faker\Factory;
use Faker\Generator;
use Nelmio\Alice\Loader\NativeLoader;
use Nelmio\Alice\ObjectSet;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\Workflow\Registry;

/**
 * Load people into database.
 */
class LoadPeople extends AbstractFixture implements ContainerAwareInterface, OrderedFixtureInterface
{
    use \Symfony\Component\DependencyInjection\ContainerAwareTrait;

    final public const PERSON = 'person';

    /**
     * @var array|Center[]
     */
    protected array $cacheCenters = [];

    /**
     * @var array|Country[]
     */
    protected array $cacheCountries = [];

    /**
     * @var array|MaritalStatus[]
     */
    protected array $cacheMaritalStatuses = [];

    /**
     * @var array|Scope[]
     */
    protected array $cacheScopes = [];

    /**
     * @var array|SocialIssue[]
     */
    protected array $cacheSocialIssues = [];

    /**
     * @var array|User[]
     */
    protected array $cacheUsers = [];

    /**
     * @var array|Gender[]
     */
    protected array $cacheGenders = [];

    protected Generator $faker;

    protected NativeLoader $loader;

    private array $peoples = [
        [
            'lastName' => 'Depardieu',
            'firstName' => 'Gérard',
            'birthdate' => '1948-12-27',
            'placeOfBirth' => 'Châteauroux',
            'nationality' => 'RU',
            'gender' => GenderEnum::MALE,
            'center' => 'Center A',
            'accompanyingPeriods' => [
                [
                    'from' => '2015-02-01',
                    'to' => '2015-10-30',
                    'remark' => 'oops',
                ], [
                    'from' => '2017-06-01',
                    'to' => '2018-03-30',
                    'remark' => 'argg',
                ], [
                    'from' => '2019-01-01',
                    'to' => '2019-12-31',
                    'remark' => 'blob',
                ],
            ],
        ],
        [
            // to have a person with same firstname as Gérard Depardieu
            'lastName' => 'Depardieu',
            'firstName' => 'Jean',
            'birthdate' => '1960-10-12',
            'countryOfBirth' => 'FR',
            'nationality' => 'FR',
            'center' => 'Center A',
            'maritalStatus' => 'ms_divorce',
        ],
        [
            // to have a person with same birthdate as Gérard Depardieu
            'lastName' => 'Van Snick',
            'firstName' => 'Bart',
            'birthdate' => '1948-12-27',
            'center' => 'Center A',
            'maritalStatus' => 'ms_legalco',
        ],
        [
            // to have a woman with Depardieu as FirstName
            'lastName' => 'Depardieu',
            'firstName' => 'Charline',
            'birthdate' => '1970-10-15',
            'gender' => GenderEnum::FEMALE,
            'center' => 'Center A',
            'maritalStatus' => 'ms_legalco',
        ],
        [
            // to have a special character in lastName
            'lastName' => 'Manço',
            'firstName' => 'Étienne',
            'center' => 'Center A',
            'maritalStatus' => 'ms_unknown',
        ],
        [
            // to have true duplicate person
            'lastName' => 'Depardieu',
            'firstName' => 'Jean',
            'birthdate' => '1960-10-12',
            'countryOfBirth' => 'FR',
            'nationality' => 'FR',
            'center' => 'Center A',
            'maritalStatus' => 'ms_divorce',
        ],
        [
            // to have false duplicate person
            'lastName' => 'Depardieu',
            'firstName' => 'Jeanne',
            'birthdate' => '1966-11-13',
            'countryOfBirth' => 'FR',
            'nationality' => 'FR',
            'center' => 'Center A',
            'maritalStatus' => 'ms_legalco',
        ],
        [
            'lastName' => 'Diallo',
            'firstName' => 'Fatoumata Binta',
        ],
        [
            'lastName' => 'Diallo',
            'firstName' => 'Abdoulaye',
        ],
        [
            'lastName' => 'Diallo',
            'firstName' => 'Diakite',
        ],
        [
            'lastName' => 'Diallo',
            'firstName' => 'Mohamed',
        ],
        [
            'lastName' => 'Diallo',
            'firstName' => 'Fatou',
        ],
        [
            'lastName' => 'Diallo',
            'firstName' => 'Fanta',
        ],
        [
            'lastName' => 'Bah',
            'firstName' => 'Fatoumata Binta',
        ],
        [
            'lastName' => 'Bah',
            'firstName' => 'Abdoulaye',
        ],
        [
            'lastName' => 'Bah',
            'firstName' => 'Diakite',
        ],
        [
            'lastName' => 'Bah',
            'firstName' => 'Mohamed',
        ],
        [
            'lastName' => 'Bah',
            'firstName' => 'Fatou',
        ],
        [
            'lastName' => 'Bah',
            'firstName' => 'Fanta',
        ],
        [
            'lastName' => 'Bah',
            'firstName' => 'Gaston',
        ],
        [
            'lastName' => 'Gaillot',
            'firstName' => 'Adèle',
        ],
    ];

    public function __construct(
        protected Registry $workflowRegistry,
        protected SocialIssueRepository $socialIssueRepository,
        protected CenterRepository $centerRepository,
        protected CountryRepository $countryRepository,
        protected MaritalStatusRepository $maritalStatusRepository,
        protected ScopeRepository $scopeRepository,
        protected UserRepository $userRepository,
        protected GenderRepository $genderRepository,
    ) {
        $this->faker = Factory::create('fr_FR');
        $this->faker->addProvider($this);
        $this->loader = new NativeLoader($this->faker);
    }

    public function getOrder(): int
    {
        return 10000;
    }

    /**
     * @internal This method is public and called by faker as a custom generator
     */
    public function getRandomCenter(): Center
    {
        if (0 === \count($this->cacheCenters)) {
            $this->cacheCenters = $this->centerRepository->findAll();
        }

        return $this->cacheCenters[array_rand($this->cacheCenters)];
    }

    /**
     * @internal This method is public and called by faker as a custom generator
     *
     * @throws \Exception
     */
    public function getRandomCountry(int $nullPercentage = 20): ?Country
    {
        if (0 === \count($this->cacheCountries)) {
            $this->cacheCountries = $this->countryRepository->findAll();
        }

        if (\random_int(0, 100) > $nullPercentage) {
            return null;
        }

        return $this->cacheCountries[array_rand($this->cacheCountries)];
    }

    /**
     * @internal This method is public and called by faker as a custom generator
     */
    public function getRandomGender(int $nullPercentage = 50): ?Gender
    {
        if (0 === \count($this->cacheGenders)) {
            $this->cacheGenders = $this->genderRepository->findByActiveOrdered();
        }

        if (\random_int(0, 100) > $nullPercentage) {
            return null;
        }

        return $this->cacheGenders[array_rand($this->cacheGenders)];
    }

    /**
     * @internal This method is public and called by faker as a custom generator
     *
     * @throws \Exception
     */
    public function getRandomMaritalStatus(int $nullPercentage = 50): ?MaritalStatus
    {
        if (0 === \count($this->cacheMaritalStatuses)) {
            $this->cacheMaritalStatuses = $this->maritalStatusRepository->findAll();
        }

        if (\random_int(0, 100) > $nullPercentage) {
            return null;
        }

        return $this->cacheMaritalStatuses[array_rand($this->cacheMaritalStatuses)];
    }

    public function load(ObjectManager $manager): void
    {
        $this->loadExpectedPeople($manager);
        $this->loadRandPeople($manager);

        $manager->flush();
    }

    public function loadExpectedPeople(ObjectManager $manager)
    {
        echo "loading expected people...\n";

        foreach ($this->peoples as $personDef) {
            $person = $this->createExpectedPerson($personDef);
            $this->addAPerson($person, $manager);
        }
    }

    protected function loadRandPeople(ObjectManager $manager)
    {
        echo "loading rand people...\n";
        $persons = $this->createRandPerson()->getObjects();

        foreach ($persons as $person) {
            $this->addAPerson($person, $manager);
        }
    }

    /**
     * create a new person from array data.
     *
     * @throws \Exception
     */
    private function addAPerson(Person $person, ObjectManager $manager)
    {
        $accompanyingPeriod = new AccompanyingPeriod(
            (new \DateTime())
                ->sub(
                    new \DateInterval('P'.\random_int(0, 180).'D')
                )
        );
        $accompanyingPeriod->setCreatedBy($this->getRandomUser())
            ->setCreatedAt(new \DateTimeImmutable('now'));
        $person->addAccompanyingPeriod($accompanyingPeriod);
        $accompanyingPeriod->addSocialIssue($this->getRandomSocialIssue());

        if (\random_int(0, 10) > 3) {
            // always add social scope:
            $accompanyingPeriod->addScope($this->getReference('scope_social', Scope::class));
            $origin = $this->getReference(LoadAccompanyingPeriodOrigin::ACCOMPANYING_PERIOD_ORIGIN, AccompanyingPeriod\Origin::class);
            $accompanyingPeriod->setOrigin($origin);
            $accompanyingPeriod->setIntensity('regular');
            $userJob = $this->getReference(LoadUserJob::USER_JOB, UserJob::class);
            $accompanyingPeriod->setJob($userJob);
            $administrativeLocation = $this->getReference(LoadAdministrativeLocation::ADMINISTRATIVE_LOCATION, Location::class);
            $accompanyingPeriod->setAdministrativeLocation($administrativeLocation);
            $accompanyingPeriod->setAddressLocation($this->createAddress());
            $manager->persist($accompanyingPeriod->getAddressLocation());
            $workflow = $this->workflowRegistry->get($accompanyingPeriod);
            $workflow->apply($accompanyingPeriod, 'confirm');
        }

        $manager->persist($person);
        $manager->persist($accompanyingPeriod);

        $this->addReference(self::PERSON.$person->getId(), $person);
    }

    private function createAddress(): Address
    {
        $objectSet = $this->loader->loadData([
            Address::class => [
                'address' => [
                    'street' => '<fr_FR:streetName()>',
                    'streetNumber' => '<fr_FR:buildingNumber()>',
                    'validFrom' => '<dateTimeBetween(\'-1 year\', \'now\')>',
                    'postCode' => $this->getPostalCode(),
                ],
            ],
        ]);

        return $objectSet->getObjects()['address'];
    }

    private function createExpectedPerson($default): Person
    {
        /** @var Person $person */
        $person = $this->loader->loadData([
            Person::class => [
                'person' => [
                    'firstName' => $default['firstName'] ?? '<firstname()>',
                    'lastName' => $default['lastName'] ?? '<lastname()>',
                    'gender' => '<getRandomGender()>',
                    'nationality' => '<getRandomCountry()>',
                    'center' => '<getRandomCenter()>',
                    'maritalStatus' => '<getRandomMaritalStatus()>',
                    'birthdate' => '<dateTimeBetween("-75 years", "-1 tears")>',
                    'placeOfBirth' => '<city()>',
                    'email' => '<freeEmail()>',
                    'countryOfBirth' => '<getRandomCountry(80)>',
                ],
            ],
        ])->getObjects()['person'];

        // force some values
        foreach ($default as $key => $value) {
            switch ($key) {
                case 'birthdate':
                    $person->setBirthdate(new \DateTime($value));

                    break;

                case 'center':
                    $person->setCenter($this->centerRepository
                        ->findOneBy(['name' => $value]));

                    break;

                case 'countryOfBirth':
                    $country = $this->countryRepository
                        ->findOneBy(['countryCode' => $value]);
                    $person->setCountryOfBirth($country);

                    break;
                case 'nationality':
                    $country = $this->countryRepository
                        ->findOneBy(['countryCode' => $value]);
                    $person->setNationality($country);

                    break;

                case 'maritalStatus':
                    $person->setMaritalStatus($this->maritalStatusRepository
                        ->find($value));

                    break;
            }
        }

        return $person;
    }

    private function createRandPerson(): ObjectSet
    {
        return $this->loader->loadData([
            Person::class => [
                'persons{1..300}' => [
                    'firstName' => '<firstname()>',
                    'lastName' => '<lastname()>',
                    'gender' => '<getRandomGender()>',
                    'nationality' => '<getRandomCountry()>',
                    'center' => '<getRandomCenter()>',
                    'maritalStatus' => '<getRandomMaritalStatus()>',
                    'birthdate' => '<dateTimeBetween("-75 years", "-1 tears")>',
                    'placeOfBirth' => '<city()>',
                    'email' => '<freeEmail()>',
                    'countryOfBirth' => '<getRandomCountry(80)>',
                ],
            ],
        ]);
    }

    private function getPostalCode(): PostalCode
    {
        $ref = LoadPostalCodes::$refs[array_rand(LoadPostalCodes::$refs)];

        return $this->getReference($ref, PostalCode::class);
    }

    private function getRandomSocialIssue(): SocialIssue
    {
        if (0 === \count($this->cacheSocialIssues)) {
            $this->cacheSocialIssues = $this->socialIssueRepository->findAll();
        }

        return $this->cacheSocialIssues[array_rand($this->cacheSocialIssues)];
    }

    private function getRandomUser(): User
    {
        if (0 === \count($this->cacheUsers)) {
            $this->cacheUsers = $this->userRepository->findAll();
        }

        return $this->cacheUsers[array_rand($this->cacheUsers)];
    }
}
