<?php


namespace Snaju\Inception\Route\Loaders\Func;

use Snaju\Inception\Route\RouteFile;
use Snaju\Inception\InceptionCore;
use Snaju\Inception\Route\RouteLoader;
use Snaju\Inception\Route\RouteManager;
use Snaju\Inception\Util\Loader;

class FuncRouteLoader implements RouteLoader
{

    private ?string $routeDir;

    public function __construct(string $routeDir = null)
    {
        if (!empty($templateDir) || $routeDir !== null) {
            $this->$routeDir = $routeDir;
            echo "route empty or null :D";
        }
            else {
                $this->$routeDir = config('app.routesDirectory');
            }
    }

    public function loadRoutes()
    {
        // TODO: add option to config routes directory...
        $loader = new Loader(InceptionCore::getBase() . "/" . config('app.routesDirectory'), '/.*\.(php)/mix', false);

        foreach ($loader->getMatches() as $matchLoc) {
            preg_match('/(.*)\.(php)/mi', $matchLoc, $m);
            $relative = str_replace(array(InceptionCore::getBase() . "/" . config('app.routesDirectory'), 'index'), '', $m[1]);
            $route = new FuncRoute($relative, $relative);

            $route->attach(new RouteFile(function() use ($matchLoc) {
                return require $matchLoc;
            }));

            RouteManager::register($route);
        }
    }

}