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

use Chill\AsideActivityBundle\Entity\AsideActivityCategory;
use Chill\MainBundle\Templating\Entity\ChillEntityRenderInterface;
use Chill\MainBundle\Templating\TranslatableStringHelper;

/**
 * @implements ChillEntityRenderInterface<AsideActivityCategory>
 */
final readonly class CategoryRender implements ChillEntityRenderInterface
{
    public const DEFAULT_ARGS = [
        self::SEPERATOR_KEY => ' > ',
    ];

    public const SEPERATOR_KEY = 'default.separator';

    public function __construct(private TranslatableStringHelper $translatableStringHelper, private \Twig\Environment $engine) {}

    public function buildParents(AsideActivityCategory $asideActivityCategory)
    {
        $parents = [];

        while ($asideActivityCategory->hasParent()) {
            $asideActivityCategory = $parents[] = $asideActivityCategory->getParent();
        }

        return $parents;
    }

    public function renderBox($asideActivityCategory, array $options): string
    {
        $options = array_merge(self::DEFAULT_ARGS, $options);
        $parents = $this->buildParents($asideActivityCategory);

        return $this->engine->render(
            '@ChillAsideActivity/Entity/asideActivityCategory.html.twig',
            [
                'asideActivityCategory' => $asideActivityCategory,
                'parents' => $parents,
                'options' => $options,
            ]
        );
    }

    public function renderString($asideActivityCategory, array $options): string
    {
        $options = array_merge(self::DEFAULT_ARGS, $options);

        $titles = [
            $this->translatableStringHelper->localize($asideActivityCategory->getTitle()),
        ];

        while ($asideActivityCategory->hasParent()) {
            $asideActivityCategory = $asideActivityCategory->getParent();
            $titles[] = $this->translatableStringHelper->localize($asideActivityCategory->getTitle());
        }

        $titles = array_reverse($titles);

        return implode($options[self::SEPERATOR_KEY], $titles);
    }

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