<?php

namespace App;

use App\Controller\BaseController;
use Shared\Log;
use Twig\Loader\FilesystemLoader;

class AppCreator
{
    private Container $container;

    private array $services = [];

    public function __construct()
    {
        $this->container = new Container;
    }

    public function registerService(string $serviceId, callable|string $service): self
    {
        $this->container->set($serviceId, $service);
        $this->services[] = $serviceId;
        return $this;
    }

    /**
     * Create an instance or perform actions based on the current application environment.
     *
     * @return App|null An instance of the App class in the 'development' environment, or null in other environments.
     */
    public function create(): ?App
    {
        // Check the application environment
        switch (APP_ENV) {
            case 'console':
                // Load the Console.php file in case of the 'console' environment
                require_once __DIR__ . '/../console/Console.php';
                break;
            case 'development':
                // Create a new instance of the App class in the 'development' environment
                return new App("HeartTrack", 1, $this->container);
                break;
            case 'html':
                // Load the index.test.php file in case of the 'html' environment
                require_once __DIR__ . '/index.test.php';
                break;
            default:
                // Handle other environment cases here, if necessary
                break;
        }
        return null;
    }



    function AddControllers($namespacePrefix = 'App\Controller', $pathToControllers = __DIR__ . '/controller'): self
    {
        $controllerFiles = glob($pathToControllers . '/*.php');

        foreach ($controllerFiles as $file) {
            // Get class name from file name
            $class = basename($file, '.php');
            $fullClassName = $namespacePrefix . '\\' . $class;
            if (!class_exists($fullClassName)) {
                continue;
            }

            // Use reflection to check if class extends BaseController
            $reflectionClass = new \ReflectionClass($fullClassName);
            if ($reflectionClass->isSubclassOf(BaseController::class)) {
                // Register in DI container
                $this->container->set($fullClassName, function () use ($fullClassName) {
                    $controllerInstance = new $fullClassName();
                    $controllerInstance->setContainer($this->container);
                    return $controllerInstance;
                });

            }
        }

        return $this;
    }

    public function getServiceRegistered(): array
    {
        return $this->services;
    }
}


