<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\Hook\Front;

use Gls\GlsPoland\Asset\AssetManagerInterface;
use Gls\GlsPoland\PrestaShop\Checkout\CheckoutResolverInterface;
use Gls\GlsPoland\PrestaShop\Hook\HookInterface;
use Symfony\Component\HttpFoundation\Request;

final class ActionFrontControllerSetMedia implements HookInterface
{
    public const HOOK_NAME = 'actionFrontControllerSetMedia';

    private $assetManager;
    private $checkoutResolver;

    public function __construct(CheckoutResolverInterface $checkoutResolver, AssetManagerInterface $assetManager)
    {
        $this->checkoutResolver = $checkoutResolver;
        $this->assetManager = $assetManager;
    }

    /**
     * @param array{request: Request, cart: \Cart} $parameters
     */
    public function execute(array $parameters): void
    {
        $cart = $parameters['cart'] ?? null;
        $request = $parameters['request'] ?? null;

        if (!$cart instanceof \Cart || !$request instanceof Request || $request->isXmlHttpRequest()) {
            return;
        }

        if (null === $checkout = $this->checkoutResolver->resolve($request)) {
            return;
        }

        $assets = $checkout->getAssets($cart);

        foreach ($assets->getJavaScripts() as $path => $options) {
            $this->assetManager->registerJavaScript($path, $options);
        }

        foreach ($assets->getStyleSheets() as $path => $options) {
            $this->assetManager->registerStyleSheet($path, $options);
        }

        $this->assetManager->registerJavaScriptVariables($assets->getJavaScriptVariables());
    }
}
