<?php

namespace Opentalent\OtCore\Cache;

use Opentalent\OtCore\Website\OtPageRepository;
use TYPO3\CMS\Core\Service\OpcodeCacheService;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManager;
use TYPO3\CMS\Install\Service\ClearCacheService;
use TYPO3\CMS\Core\Cache\CacheManager;

class OtCacheManager
{
    /**
     * Clears the page cache
     *
     * @param int $pageUid
     */
    public static function clearPageCache(int $pageUid) {
        $cacheManager = GeneralUtility::makeInstance(CacheManager::class);
        $cacheManager->flushCachesInGroupByTag(
            'pages',
            'pageId_' . $pageUid
        );
    }

    /**
     * Clears cache for each page of the site
     *
     * @param int $pageUid
     * @param bool $clearAll if true, all caches will be cleared, and not only the frontend one
     */
    public static function clearSiteCache(int $pageUid, $clearAll=false) {

        $pageRepository = GeneralUtility::makeInstance(ObjectManager::class)->get(OtPageRepository::class);
        $rootPage = $pageRepository->getRootPageFor($pageUid);
        $pages = $pageRepository->getAllSubpagesForPage($rootPage['uid']);
        $pages[] = $rootPage;

        $cacheManager = GeneralUtility::makeInstance(CacheManager::class);

        $tags = array_map(function ($page) {
            return 'pageId_' . $page['uid'];
        }, $pages);

        if (!$clearAll) {
            $cacheManager->flushCachesInGroupByTags('pages', $tags);
        } else {
            $cacheManager->flushCachesByTags($tags);
        }
    }

    /**
     * Clear cache framework and opcode caches
     *
     * @see TYPO3\CMS\Install\Controller\MaintenanceController
     */
    public static function clearAllCache()
    {
        $cacheManager = GeneralUtility::makeInstance(CacheManager::class);
        $cacheManager->flushCaches();
//        GeneralUtility::makeInstance(ClearCacheService::class)->clearAll();
//        GeneralUtility::makeInstance(OpcodeCacheService::class)->clearAllActive();
    }
}
