<?php

namespace AutoAdmin\Bundle\Seo\Sitemap;

use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\CacheItem;
use Symfony\Contracts\Cache\CacheInterface;
use Thepixeldeveloper\Sitemap\Drivers\XmlWriterDriver;

class SitemapRenderer
{
    private const CACHE_NAMESPACE = 'aa.sitemap.cache';
    private const CACHE_LIFETIME = 3600 * 24; // 24 hour

    private SitemapManager $manager;
    private CacheInterface $cache;

    public function __construct(SitemapManager $manager, string $projectDirectory)
    {
        $this->manager = $manager;
        $this->cache = new FilesystemAdapter(
            self::CACHE_NAMESPACE,
            self::CACHE_LIFETIME,
            $projectDirectory . '/var/cache/autoadmin'
        );
    }

    public function render($hostAndScheme, string $section = 'default', bool $forceRefresh = false): ?string
    {
        $cacheKey = md5('SitemapRenderer::render(' . $hostAndScheme . ', ' . $section . ')');
        if ($this->cache->hasItem($cacheKey) && $forceRefresh === false) {
            return $this->cache->getItem($cacheKey)->get();
        }

        $urlSets = $this->manager->build($hostAndScheme, $section);

        if (!isset($urlSets[$section])) {
            return null;
        }

        $urlset = $urlSets[$section];
        $driver = new XmlWriterDriver();
        $urlset->accept($driver);

        /** @var CacheItem $cacheItem */
        $cacheItem = $this->cache->getItem($cacheKey);
        $cacheItem->set($driver->output());
        $this->cache->save($cacheItem);

        return $cacheItem->get();
    }

    public function getSections(): array
    {
        return $this->manager->getSections();
    }
}
