<?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\Templating\Entity;

use Chill\MainBundle\Templating\Entity\BoxUtilsChillEntityRenderTrait;
use Chill\MainBundle\Templating\Entity\ChillEntityRenderInterface;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Chill\PersonBundle\Entity\AccompanyingPeriod\ClosingMotive;
use Symfony\Contracts\Translation\TranslatorInterface;

/**
 * Render closing motive.
 *
 * @implements ChillEntityRenderInterface<ClosingMotive>
 */
final readonly class ClosingMotiveRender implements ChillEntityRenderInterface
{
    use BoxUtilsChillEntityRenderTrait;
    private const SEPARATOR = ' > ';

    public function __construct(
        private TranslatableStringHelperInterface $translatableStringHelper,
        private TranslatorInterface $translator,
    ) {}

    public function renderBox($entity, array $options): string
    {
        return
            $this->getDefaultOpeningBox('closing-motive').
            $this->renderString($entity, $options).
            $this->getDefaultClosingBox();
    }

    public function renderString($entity, array $options): string
    {
        return $this->renderStringRecursive(
            $entity,
            '',
            $options
        );
    }

    public function supports($entity, array $options): bool
    {
        return $entity instanceof ClosingMotive;
    }

    private function renderStringRecursive(ClosingMotive $motive, string $existing, array $options): string
    {
        $str = $this->translatableStringHelper->localize($motive->getName());

        if ($motive->hasParent()) {
            if ('' !== $existing) {
                $str = $str.self::SEPARATOR.$existing;
            }

            $str = $this->renderStringRecursive(
                $motive->getParent(),
                $str,
                $options
            );
        }

        if ('' !== $existing) {
            $str = $str.self::SEPARATOR.$existing;
        }

        if ($motive->isLeaf() && $motive->isCanceledAccompanyingPeriod()) {
            $str = $str.' '.$this->translator->trans('( Canceled period )');
        }

        return $str;
    }
}
