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

use Chill\MainBundle\Entity\Language;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Load languages into database.
 */
class LoadLanguages extends AbstractFixture implements ContainerAwareInterface, OrderedFixtureInterface
{
    // Array of ancien languages (to exclude)
    private array $ancientToExclude = ['ang', 'egy', 'fro', 'goh', 'grc', 'la', 'non', 'peo', 'pro', 'sga',
        'dum', 'enm', 'frm', 'gmh', 'mga', 'akk', 'phn', 'zxx', 'got', 'und', ];

    private ?ContainerInterface $container = null;

    // The regional version of language are language with _ in the code
    // This array contains regional code to not exclude
    private array $regionalVersionToInclude = ['ro_MD'];

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

    public function load(ObjectManager $manager): void
    {
        echo "loading languages... \n";

        foreach (\Symfony\Component\Intl\Languages::getNames() as $code => $language) {
            if (
                !\in_array($code, $this->regionalVersionToInclude, true)
                && !\in_array($code, $this->ancientToExclude, true)
            ) {
                $lang = (new Language())
                    ->setId($code)
                    ->setName($this->prepareName($code));
                $manager->persist($lang);
            }
        }

        $manager->flush();
    }

    public function setContainer(?ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    /**
     * Prepare names for languages.
     *
     * @return string[] languages name indexed by available language code
     */
    private function prepareName(string $languageCode): array
    {
        $names = [];

        foreach ($this->container->getParameter('chill_main.available_languages') as $lang) {
            $names[$lang] = \Symfony\Component\Intl\Languages::getName($languageCode, $lang);
        }

        return $names;
    }
}
