<?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\Export;

use Chill\MainBundle\Entity\User;
use Symfony\Component\Security\Core\Security;
use Symfony\Contracts\Translation\TranslatableInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

/**
 * Give an explanation of an export.
 */
final readonly class ExportDescriptionHelper
{
    public function __construct(
        private ExportManager $exportManager,
        private ExportConfigNormalizer $exportConfigNormalizer,
        private ExportConfigProcessor $exportConfigProcessor,
        private TranslatorInterface $translator,
        private Security $security,
    ) {}

    /**
     * @return list<string>
     */
    public function describe(string $exportAlias, array $exportOptions, bool $includeExportTitle = true): array
    {
        $output = [];
        $denormalized = $this->exportConfigNormalizer->denormalizeConfig($exportAlias, $exportOptions);
        $user = $this->security->getUser();

        if ($includeExportTitle) {
            $output[] = $this->trans($this->exportManager->getExport($exportAlias)->getTitle());
        }

        if (!$user instanceof User) {
            return $output;
        }
        $context = new ExportGenerationContext($user);

        foreach ($this->exportConfigProcessor->retrieveUsedFilters($denormalized['filters']) as $name => $filter) {
            $output[] = $this->trans($filter->describeAction($denormalized['filters'][$name]['form'], $context));
        }

        foreach ($this->exportConfigProcessor->retrieveUsedAggregators($denormalized['aggregators']) as $name => $aggregator) {
            $output[] = $this->trans($aggregator->getTitle());
        }

        return $output;
    }

    private function trans(string|TranslatableInterface|array $translatable): string
    {
        if (is_string($translatable)) {
            return $this->translator->trans($translatable);
        }

        if ($translatable instanceof TranslatableInterface) {
            return $translatable->trans($this->translator);
        }

        // array case
        return $this->translator->trans($translatable[0], $translatable[1] ?? []);
    }
}
