<?php

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Service;

use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Adapter\PhpArrayAdapter;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpKernel\KernelInterface;

/**
 * Permet de charger automatiquelent les extensions de form qui se trouve dans les bundles sous templates > extends > form > front.
 */
class FormThemeLocator
{
    /** @var list<string> */
    private const REQUIRED_FORM_THEMES = [
        '@CpCreationAltcha/form/altcha_theme.html.twig',
    ];

    private string $cacheFile;
    private string $projectDir;
    /**
     * @var array<string, string>
     */
    private array $bundlePaths;

    public function __construct(KernelInterface $kernel)
    {
        $this->projectDir = $kernel->getProjectDir();
        $this->cacheFile = $kernel->getCacheDir().'/viticore/form_theme_app_cache.php';
        $this->bundlePaths = array_map(
            static fn ($bundle) => $bundle->getPath(),
            $kernel->getBundles()
        );
    }

    /**
     * @return string[]
     */
    public function getAppFormThemes(): array
    {
        $cache = new PhpArrayAdapter($this->cacheFile, new FilesystemAdapter());
        $item = $cache->getItem('app_form_themes');

        if ($item->isHit()) {
            return $item->get();
        }

        return $this->scanThemes();
    }

    /**
     * @return string[]
     */
    public function scanThemes(): array
    {
        $themes = self::REQUIRED_FORM_THEMES;

        foreach ($this->bundlePaths as $bundlePath) {
            $bundleExtendsDirs = [
                $bundlePath.'/templates/extends',
                $bundlePath.'/Resources/views/extends',
            ];

            foreach ($bundleExtendsDirs as $dir) {
                if (is_dir($dir)) {
                    $themes = array_merge($themes, $this->scanTwigThemesFrom($dir));
                }
            }
        }

        $projectExtendsDirs = [
            $this->projectDir.'/templates/extends',
        ];

        foreach ($projectExtendsDirs as $dir) {
            if (is_dir($dir)) {
                $themes = array_merge($themes, $this->scanTwigThemesFrom($dir));
            }
        }

        return array_values(array_unique($themes));
    }

    /**
     * @return string[]
     */
    private function scanTwigThemesFrom(string $baseDir): array
    {
        $finder = new Finder();
        $finder
            ->files()
            ->in($baseDir)
            ->path('#(^|/)form(/|$)#') // match récursif
            ->name('*.html.twig');

        $themes = [];
        foreach ($finder as $file) {
            $relative = $file->getRelativePathname(); // ex: acme/form/input.html.twig
            $themes[] = 'extends/'.str_replace('\\', '/', $relative);
        }

        return $themes;
    }
}
