<?php

declare(strict_types=1);

namespace Gls\GlsPoland\EventDispatcher\Adapter;

use Gls\GlsPoland\EventDispatcher\EventDispatcherInterface as ModuleEventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventDispatcher as SymfonyEventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface as ContractsEventDispatcherInterface;

if (interface_exists(ContractsEventDispatcherInterface::class)) {
    class EventDispatcher implements ModuleEventDispatcherInterface
    {
        private $dispatcher;

        public function __construct(ContractsEventDispatcherInterface $dispatcher = null)
        {
            $this->dispatcher = $dispatcher ?? new SymfonyEventDispatcher();
        }

        public function dispatch(object $event, string $eventName = null)
        {
            return $this->dispatcher->dispatch($event, $eventName);
        }

        public function addSubscriber(EventSubscriberInterface $subscriber): void
        {
            $this->dispatcher->addSubscriber($subscriber);
        }
    }
} else {
    class EventDispatcher implements ModuleEventDispatcherInterface
    {
        private $dispatcher;

        public function __construct(EventDispatcherInterface $dispatcher = null)
        {
            $this->dispatcher = $dispatcher ?? new SymfonyEventDispatcher();
        }

        public function dispatch(object $event, string $eventName = null)
        {
            return $this->dispatcher->dispatch($eventName ?? get_class($event), $event);
        }

        public function addSubscriber(EventSubscriberInterface $subscriber): void
        {
            $this->dispatcher->addSubscriber($subscriber);
        }
    }
}
