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

use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

/**
 * Add the following Twig Extension :
 * * chill_custom_fields_group_widget : to render the value of a custom field
 * *   group.
 */
final class CustomFieldsGroupRenderingTwig extends AbstractExtension
{
    /**
     * @var array The default parameters
     */
    private array $defaultParams = [
        'layout' => '@ChillCustomFields/CustomFieldsGroup/render.html.twig',
        'show_empty' => true,
    ];

    /**
     * @param bool $showEmptyValues whether the empty values must be rendered
     */
    public function __construct($showEmptyValues)
    {
        $this->defaultParams['show_empty'] = $showEmptyValues;
    }

    /**
     * (non-PHPdoc).
     *
     * @see Twig_Extension::getFunctions()
     */
    public function getFunctions()
    {
        return [
            new TwigFunction('chill_custom_fields_group_widget', $this->renderWidget(...), [
                'is_safe' => [
                    'html',
                ],
                'needs_environment' => true,
            ]),
        ];
    }

    /** (non-PHPdoc).
     * @see Twig_ExtensionInterface::getName()
     */
    public function getName()
    {
        return 'chill_custom_fields_group_rendering';
    }

    /**
     * Twig extension that is used to render the value of a custom field group.
     *
     * The presentation of the value  is influenced by the document type.
     *
     * @param array             $fields           The array raw, as stored in the db
     * @param CustomFieldsGroud $customFielsGroup The custom field group
     * @param string            $documentType     The type of the document (csv, html)
     * @param array             $params           The parameters for rendering :
     *                                            - layout : allow to choose a different layout by default :
     *
     *             @ChillCustomFields/CustomFieldsGroup/render.html.twig
     *  - show_empty : force show empty field
     *
     * @return string HTML representation of the custom field group value, as described in
     *                the CustomFieldInterface. Is HTML safe
     */
    public function renderWidget(Environment $env, array $fields, $customFielsGroup, $documentType = 'html', array $params = [])
    {
        $resolvedParams = array_merge($this->defaultParams, $params);

        return $env->render($resolvedParams['layout'], [
            'cFGroup' => $customFielsGroup,
            'cFData' => $fields,
            'show_empty' => $resolvedParams['show_empty'], ]);
    }
}
