<?php

namespace Internetgalerie\IgDatapoolFe\Utility;

use TYPO3\CMS\Core\Cache\CacheManager;
use TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\SingletonInterface;
use TYPO3\CMS\Core\Database\ConnectionPool;

class CacheUtility implements SingletonInterface
{
    public $queryBuilder = null;
    public function __construct()
    {
        $this->connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
        $this->cacheManager = GeneralUtility::makeInstance(CacheManager::class);
    }



    public function urlFlushByParameter($paramName, $paramValue): void
    {
        // Delete realurl cache
        if (!$paramName || !$paramValue) {
            return;
        }
        $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tx_realurl_urldata');
        $res = $queryBuilder->select('uid')
                            ->from('tx_realurl_urldata')
                            ->where($queryBuilder->expr()->like('request_variables', $queryBuilder->createNamedParameter('%"' . $paramName . '":"'.intval($paramValue).'"%')))
                            ->executeQuery();



        $uids = [];
        while ($row = $res->fetchAssociative()) {
            $uids[] = $row['uid'];
        }
        if (count($uids)) {
            // tx_realurl_uniqalias: korrekt wäre wohl über tablename field_alias  value_id das ganze zu loeschen
            $queryBuilder=$this->connectionPool->getQueryBuilderForTable('tx_realurl_uniqalias_cache_map');
            $res = $queryBuilder->select('alias_uid')->from('tx_realurl_uniqalias_cache_map')->where($queryBuilder->expr()->in('url_cache_id', $uids))->executeQuery();
            $alias_uids=[];
            while ($row = $res->fetchAssociative()) {
                $alias_uids[]=$row['alias_uid'];
            }
            if (count($alias_uids)) {
                //var_dump($alias_uids);exit(0);
                $queryBuilder=$this->connectionPool->getQueryBuilderForTable('tx_realurl_uniqalias');
                $queryBuilder->delete('tx_realurl_uniqalias')->where($queryBuilder->expr()->in('uid', $alias_uids))->executeStatement();
            }
            // foreach mit \DmitryDulepov\Realurl\Cache\CacheFactory::getCache()->clearUrlCacheById($uid);
            $queryBuilder=$this->connectionPool->getQueryBuilderForTable('tx_realurl_uniqalias_cache_map');
            $queryBuilder->delete('tx_realurl_uniqalias_cache_map')->where($queryBuilder->expr()->in('url_cache_id', $uids))->executeStatement();

            $queryBuilder=$this->connectionPool->getQueryBuilderForTable('tx_realurl_urldata');
            $queryBuilder->delete('tx_realurl_urldata')->where($queryBuilder->expr()->in('uid', $uids))->executeStatement();
            ;
            //echo($queryBuilder->getSql());    var_dump($uids);exit(0);
        }
    }

    public function urlFlushByTablenameUid($tablename, $uid): void
    {
        // Delete realurl cache
        if (!$tablename || !$uid) {
            return;
        }
        $queryBuilder=$this->connectionPool->getQueryBuilderForTable('tx_realurl_uniqalias');
        $res = $queryBuilder->select('uid')
            ->from('tx_realurl_uniqalias')
            ->where(
                $queryBuilder->expr()->andx(
                    $queryBuilder->expr()->eq('tablename', $queryBuilder->createNamedParameter($tablename)),
                    $queryBuilder->expr()->eq('value_id', $queryBuilder->createNamedParameter($uid))
                )
            )->executeQuery();

        $alias_uids=[];
        while ($row = $res->fetchAssociative()) {
            $alias_uids[]=$row['uid'];
        }
        if (count($alias_uids)) {

            // tx_realurl_uniqalias: korrekt wäre wohl über tablename field_alias  value_id das ganze zu loeschen
            $queryBuilder=$this->connectionPool->getQueryBuilderForTable('tx_realurl_uniqalias_cache_map');
            $res = $queryBuilder->select('url_cache_id')->from('tx_realurl_uniqalias_cache_map')->where($queryBuilder->expr()->in('alias_uid', $alias_uids))->executeQuery();
            $url_cache_ids=[];
            while ($row = $res->fetchAssociative()) {
                $url_cache_ids[]=$row['url_cache_id'];
            }
            if (count($url_cache_ids)) {
                //var_dump($alias_uids);exit(0);
                // foreach mit \DmitryDulepov\Realurl\Cache\CacheFactory::getCache()->clearUrlCacheById($uid);
                $queryBuilder=$this->connectionPool->getQueryBuilderForTable('tx_realurl_uniqalias_cache_map');
                $queryBuilder->delete('tx_realurl_uniqalias_cache_map')->where($queryBuilder->expr()->in('url_cache_id', $url_cache_ids))->executeStatement();

                $queryBuilder=$this->connectionPool->getQueryBuilderForTable('tx_realurl_urldata');
                $queryBuilder->delete('tx_realurl_urldata')->where($queryBuilder->expr()->in('uid', $url_cache_ids))->executeStatement();
                ;
                //echo($queryBuilder->getSql());    var_dump($url_cache_ids);exit(0);
            }
            $queryBuilder=$this->connectionPool->getQueryBuilderForTable('tx_realurl_uniqalias');
            $queryBuilder->delete('tx_realurl_uniqalias')->where($queryBuilder->expr()->in('uid', $alias_uids))->executeStatement();
        }
    }
    public function urlFlushByEntry($entry): void
    {
        $className = $entry::class;
        $dataMapper = GeneralUtility::makeInstance(DataMapper::class);
        $tablename = $dataMapper->getDataMap($className)->getTableName();
        $this->urlFlushByTablenameUid($tablename, $entry->getUid());
    }

    public function pageFlushByTags($tags): void
    {
        $this->cacheManager->getCache('cache_pages')->flushByTags($tags);
    }
}
