<?php

namespace KupShop\GraphQLBundle\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class JsShopRefreshListener implements EventSubscriberInterface
{
    /**
     * @var SessionInterface
     */
    protected $session;

    public const SESSION_NAME = 'jsShopReload'; // trigger js_shop reload from PHP $this->session->set(JsShopRefreshListener::SESSION_NAME, true);
    public const JS_EVENT_NAME = 'jsShop:refresh'; // js event for triggering jsshop refresh
    public const PARTIAL_FAVORITES = 'favorites'; // value for js event to refresh only favorites products
    private const REFRESH_COOKIE_NAME = 'js_shop_refresh';

    public function __construct(SessionInterface $session)
    {
        $this->session = $session;
    }

    public static function getSubscribedEvents()
    {
        if (findModule(\Modules::JS_SHOP)) {
            return [
                KernelEvents::RESPONSE => [
                    ['onKernelResponse', 200],
                ],
            ];
        }

        return [];
    }

    // Sessiony které se přemění na cookie, aby jsShop věděl že se má reloadnout. Snažit se nezakládat nové eventy, použít obecnou jsShopReload (self::SESSION_NAME).
    protected $eventsToPass = ['changeCurrency', 'changeCountry', 'changeLanguage', 'adminLogin', 'orderCreated', 'cartChanged', self::SESSION_NAME];

    public function onKernelResponse(ResponseEvent $event): void
    {
        $reload = false;

        foreach ($this->eventsToPass as $eventName) {
            if ($this->session->get($eventName)) {
                $this->session->remove($eventName);
                $reload = true;
            }
        }

        if ($reload) {
            $response = $event->getResponse();
            $response->headers->setCookie(new Cookie(self::REFRESH_COOKIE_NAME, true, time() + 120 * 24 * 60 * 60, '/', null, null, false));
        }
    }
}
