<?php

/*
 * This file is part of the Serenity 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 Serenity\AdminBundle\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 > admin.
 */
class FormThemeLocator
{
    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().'/serenity/form_theme_admin_cache.php';

        $this->bundlePaths = array_map(
            fn ($bundle) => $bundle->getPath(),
            $kernel->getBundles()
        );
    }

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

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

        return $this->scanThemes();
    }

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

        // Bundles : Resources/views/extends/**/form/admin/
        foreach ($this->bundlePaths as $bundlePath) {
            $dir = $bundlePath.'/templates/extends';
            if (is_dir($dir)) {
                $themes = array_merge($themes, $this->scanTwigThemesFrom($dir));
            }
        }

        $themes = is_dir($this->projectDir.'/templates/extends')
            ? array_merge($themes, $this->scanTwigThemesFrom($this->projectDir.'/templates/extends'))
            : $themes;

        return array_unique($themes);
    }

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

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

        return $themes;
    }
}
