<?php

use KupShop\KupShopBundle\Context\LanguageContext;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

function smarty_block_insert_cached($params, $content, &$smarty, &$repeat)
{
    $param_defaults = [
        'ttl' => 3600,
    ];
    $params = array_merge($param_defaults, $params);

    if (empty($params['key'])) {
        throw new InvalidArgumentException('Missing parameter \'key\'!');
    }

    $languageContext = ServiceContainer::getService(LanguageContext::class);

    $template = $smarty->template_resource;
    if (is_array($params['key'])) {
        array_push($params['key'], $template);
        $params['key'][] = $languageContext->getActiveId();
    } else {
        $params['key'] = [
            $template,
            $params['key'],
            $languageContext->getActiveId(),
        ];
    }
    $cacheName = join('_', $params['key']);

    if ($cachedContent = getCache($cacheName)) {
        $repeat = false;

        return $cachedContent;
    }

    if ($content !== null) {
        htmlCompress($content);
        setCache($cacheName, $content, $params['ttl']);

        return $content;
    }
}

function htmlCompress(&$html)
{
    preg_match_all('!(<(?:code|pre).*>[^<]+</(?:code|pre)>)!', $html, $pre); // exclude pre or code tags

    $html = preg_replace('!<(?:code|pre).*>[^<]+</(?:code|pre)>!', '#pre#', $html); // removing all pre or code tags

    $html = preg_replace('#<!–[^\[].+–>#', '', $html); // removing HTML comments

    $html = preg_replace('/[\r\n\t]+/', ' ', $html); // remove new lines, spaces, tabs

    $html = preg_replace('/>[\s]+</', '><', $html); // remove new lines, spaces, tabs

    $html = preg_replace('/[\s]+/', ' ', $html); // remove new lines, spaces, tabs

    if (!empty($pre[0])) {
        foreach ($pre[0] as $tag) {
            $html = preg_replace('!#pre#!', $tag, $html, 1);
        }
    }// putting back pre|code tags
}
