<?php

namespace KupShop\ComponentsBundle\Twig\Extension;

use KupShop\KupShopBundle\Context\ContextManager;
use KupShop\KupShopBundle\Context\CurrencyContext;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\KupShopBundle\Util\Price\Price;
use KupShop\KupShopBundle\Util\Price\TotalPrice;
use Twig\Extension\RuntimeExtensionInterface;

class PriceRuntime implements RuntimeExtensionInterface
{
    public function formatPrice(Price|TotalPrice $price, $withVat = null, $ceil = null, $decimal = null, $format = null, $printcurrency = null, $usePriceCurrency = null): string
    {
        $param = [
            'withVat' => $withVat,
            'ceil' => $ceil,
            'decimal' => $decimal,
            'format' => $format,
            'printcurrency' => $printcurrency,
        ];
        $param = array_filter($param, fn ($value) => !is_null($value));

        if ($usePriceCurrency) {
            $contextManager = ServiceContainer::getService(ContextManager::class);

            return $contextManager->activateContexts([CurrencyContext::class => $price->getCurrency()->getId()],
                fn () => printPrice($price, $param)
            );
        }

        return printPrice($price, $param);
    }
}
