<?php

/** @noinspection PhpRedundantCatchClauseInspection */

namespace DefStudio\GameEngine\Providers;

use ReflectionClass;
use Illuminate\Support\Reflector;
use Symfony\Component\Finder\Finder;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        $listeners_namespace = '\DefStudio\GameEngine\Listeners';
        $listeners_namespace = str($listeners_namespace)->remove("\DefStudio\GameEngine\\")->replace('\\', DIRECTORY_SEPARATOR)->toString();

        $finder = new Finder();
        $files = $finder->files()->in(__DIR__."/../$listeners_namespace");

        foreach ($files as $file) {
            $base_path = str(__DIR__)->before('/Providers');
            $listener_class = str($file->getRealPath())
                ->replaceFirst($base_path, 'DefStudio\GameEngine')
                ->replace(DIRECTORY_SEPARATOR, '\\')
                ->remove('.php')
                ->toString();

            if (class_exists($listener_class)) {
                $listener = new ReflectionClass($listener_class);

                if (!$listener->isInstantiable()) {
                    continue;
                }

                if (!$listener->hasMethod('handle')) {
                    continue;
                }

                $method = $listener->getMethod('handle');

                $event = Reflector::getParameterClassName($method->getParameters()[0]);

                Event::listen($event, $listener_class);
            }
        }
    }
}
