<?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\CustomFieldsBundle\CustomFields;

use Chill\CustomFieldsBundle\Entity\CustomField;
use Chill\CustomFieldsBundle\Form\Type\CustomFieldsTitleType;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Twig\Environment;

class CustomFieldTitle extends AbstractCustomField
{
    final public const TYPE = 'type';

    final public const TYPE_SUBTITLE = 'subtitle';

    final public const TYPE_TITLE = 'title';

    public function __construct(
        private readonly Environment $templating,
        /**
         * @var TranslatableStringHelper Helper that find the string in current locale from an array of translation
         */
        private readonly TranslatableStringHelper $translatableStringHelper,
    ) {}

    public function buildForm(FormBuilderInterface $builder, CustomField $customField)
    {
        $builder->add($customField->getSlug(), CustomFieldsTitleType::class, [
            'label' => false,
            'attr' => [
                'class' => 'cf-title',
                'title' => $this->translatableStringHelper->localize($customField->getName()),
                self::TYPE => $customField->getOptions()[self::TYPE],
            ],
        ]);
    }

    public function buildOptionsForm(FormBuilderInterface $builder)
    {
        return $builder->add(
            self::TYPE,
            ChoiceType::class,
            [
                'choices' => [
                    'Main title' => self::TYPE_TITLE,
                    'Subtitle' => self::TYPE_SUBTITLE,
                ],
                'label' => 'Title level',
            ]
        );
    }

    public function deserialize($serialized, CustomField $customField)
    {
        return $serialized;
    }

    public function getName()
    {
        return 'Title';
    }

    public function isEmptyValue($value, CustomField $customField)
    {
        return false;
    }

    public function render($value, CustomField $customField, $documentType = 'html')
    {
        return $this->templating
            ->render(
                '@ChillCustomFields/CustomFieldsRendering/title.html.twig',
                [
                    'title' => $customField->getName(),
                    'type' => $customField->getOptions()[self::TYPE],
                ]
            );
    }

    public function serialize($value, CustomField $customField)
    {
        return $value;
    }
}
