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

use Chill\MainBundle\Entity\Embeddable\CommentEmbeddable;
use Chill\MainBundle\Repository\UserRepositoryInterface;

/**
 * @implements ChillEntityRenderInterface<CommentEmbeddable>
 */
class CommentRender implements ChillEntityRenderInterface
{
    use BoxUtilsChillEntityRenderTrait;

    public function __construct(private readonly UserRepositoryInterface $userRepository, private readonly \Twig\Environment $engine) {}

    public function renderBox($entity, array $options): string
    {
        // default options
        $options = \array_merge([
            'user' => [],
            'disable_markdown' => false,
            'limit_lines' => null,
            'metadata' => true,
        ], $options);

        if (null !== $entity->getUserId()) {
            $user = $this->userRepository->find($entity->getUserId());
        }

        return $this->engine
            ->render(
                '@ChillMain/Entity/CommentEmbeddable.html.twig',
                [
                    'opening_box' => $this->getDefaultOpeningBox('comment-embeddable'),
                    'closing_box' => $this->getDefaultClosingBox(),
                    'user' => $user ?? null,
                    'comment' => $entity,
                    'options' => $options,
                ]
            );
    }

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

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