<?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\PersonIdentifier\Rendering;

use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\PersonIdentifier\PersonIdentifierManagerInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

final readonly class PersonIdRendering implements PersonIdRenderingInterface
{
    private string $idContentText;

    public function __construct(
        ParameterBagInterface $parameterBag,
        private PersonIdentifierManagerInterface $personIdentifierManager,
    ) {
        $this->idContentText = $parameterBag->get('chill_person')['person_render']['id_content_text'];
    }

    public function renderPersonId(Person $person): string
    {
        $args = [
            '[[ person_id ]]' => $person->getId(),
        ];

        foreach ($person->getIdentifiers() as $identifier) {
            if (!$identifier->getDefinition()->isActive()) {
                continue;
            }

            $key = 'identifier_'.$identifier->getDefinition()->getId();

            $args
                += [
                    "[[ {$key} ]]" => $this->personIdentifierManager->buildWorkerByPersonIdentifierDefinition($identifier->getDefinition())
                        ->renderAsString($identifier),
                    "[[ if:{$key} ]]" => '',
                    "[[ endif:{$key} ]]" => '',
                ];
            // we remove the eventual conditions


        }

        $rendered = strtr($this->idContentText, $args);

        // Delete the conditions which are not met, for instance:
        // [[ if:identifier_99 ]] ... [[ endif:identifier_99 ]]
        // this match the same dumber for opening and closing of the condition
        return preg_replace(
            '/\[\[\s*if:identifier_(\d+)\s*\]\].*?\[\[\s*endif:identifier_\1\s*\]\]/s',
            '',
            $rendered
        );
    }
}
