<?php

namespace Opentalent\OtCore\Cache;

use Opentalent\OtCore\Website\OtPageRepository;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManager;
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, bool $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->flushCachesByTags($tags);
        } else {
            $cacheManager->flushCachesInGroupByTags('pages', $tags);
        }

        // << BUGFIX: without this, the fluid templates caches are not cleared
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
        $cnn = $connectionPool->getConnectionByName('Default');
        $cnn->beginTransaction();
        $sql = "update typo3.cache_hash h inner join typo3.cache_hash_tags t on h.id = t.id
                set h.expires = 0
                where t.tag = 'ident_TS_TEMPLATE';";
        $stmt = $cnn->prepare($sql);
        $stmt->executeQuery();
        $cnn->commit();
        // >>
    }

    /**
     * Clears cache
     *
     * @param bool $clearAll if true, all caches will be cleared, and not only the frontend one
     */
    public static function clearCache($clearAll) {
        $cacheManager = GeneralUtility::makeInstance(CacheManager::class);

        if ($clearAll) {
            $cacheManager->flushCachesInGroup('pages');
        } else {
            $cacheManager->flushCaches();
        }
    }

    /**
     * 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();
    }
}
