<?php

use KupShop\ContentBundle\Exception\PageException;
use KupShop\ContentBundle\Page\FragmentPage;
use KupShop\ContentBundle\Util\PageLocator;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use Query\Operator;

function smarty_function_insert_page($params, &$smarty)
{
    if (!isset($params['type']) && !isset($params['code'])) {
        throw new InvalidArgumentException('Parameter \'type\' or \'code\' is required.');
    }

    /** @var PageLocator $pageLocator */
    $pageLocator = ServiceContainer::getService(PageLocator::class);

    static $pagesCache;

    $addToPagesCache = function (array $item) use (&$pagesCache) {
        $pagesCache['byType'][$item['type']] = $item;
        if (!empty($item['code'])) {
            $pagesCache['byCode'][$item['code']] = $item;
        }
    };

    if ($pagesCache === null) {
        $qb = sqlQueryBuilder()->select('type, code')->from('pages');

        $pagesCache = [
            'byType' => [],
            'byCode' => [],
        ];

        foreach ($qb->execute() as $item) {
            $addToPagesCache($item);
        }
    }

    if (isset($params['type'])) {
        $page = $pagesCache['byType'][$params['type']] ?? null;
        $spec = Operator::equals(['type' => $params['type']]);
    } else {
        $page = $pagesCache['byCode'][$params['code']] ?? null;
        $spec = Operator::equals(['code' => $params['code']]);
    }

    if (!$page && ($params['use_default'] ?? false)) {
        try {
            $pageService = $pageLocator->getPageService($params['type'] ?? '');
            $pageService->createPage();

            $page = sqlQueryBuilder()
                ->select('type, code')
                ->from('pages')
                ->where($spec)
                ->execute()->fetchAssociative();

            if ($page) {
                $addToPagesCache($page);
            }
        } catch (Exception $e) {
            if (isDevelopment()) {
                throw new Exception("Neexistující systémová stránka: {$params['type']}");
            }
            $page = false;
        }
    }

    if ($page) {
        $view = $smarty->getTemplateVars('view');

        $pageService = $pageLocator->getPageService($page['type']);
        if ($pageService instanceof FragmentPage) {
            $pageService->setFragmentCode($page['code']);
        }
        if ($view) {
            $pageService->setView($view);
        }

        try {
            $page = $pageService->getPage($params['placeholders'] ?? []);
        } catch (PageException $e) {
            $page = false;
        }

        $smarty->loadPlugin('Smarty_modifier_inline_edit');

        $unwrappedContent = getAdminUser() ? ($page['block']['unwrapped_content'] ?? null) : ($page['block']['content'] ?? null);
        if ($unwrappedContent || getVal('inlineEditable')) {
            $result = smarty_modifier_inline_edit($page['block']);
        } else {
            $result = false;
        }
    } else {
        $result = false;
    }

    if (!empty($params['exists'])) {
        $smarty->assign($params['exists'], (bool) $result);
    }

    if (!empty($params['assign'])) {
        $smarty->assign($params['assign'], $page);
    } else {
        return $result;
    }
}
