<?php


namespace CubiStore\Web\Utils;

class RouteCompiler
{
    private $target;
    private $root;
    private $keys;

    public function __construct($target = __DIR__ . '/../../var/cache/routes.php')
    {
        $this->target = $target;
        $this->root = Route::root();
        $this->keys = [];
    }

    public function addRoutes(array $routes, ?Route $target = null)
    {
        if ($target === null) {
            $target = $this->root;
        }

        foreach ($routes as $route => $details) {
            if (is_array($details)) {
                $routeObj = Route::group($target, $route);
                $this->addRoutes($details, $routeObj);
            }

            if (!is_string($details)) {
                continue;
            }

            $parts = explode(':', $details, 2);
            $this->keys[$parts[0]] = true;

            if ($route[0] !== '/') {
                Route::call($target, $route, '', $details);
                continue;
            }

            Route::call($target, 'GET', $route, $details);
        }
    }

    public function writeCache()
    {
        $dirname = dirname($this->target);

        if (!is_dir($dirname)) {
            mkdir($dirname, 0777, true);
        }

        file_put_contents($this->target, $this->compile());
    }

    public function compile()
    {
        $keys = array_map(function ($item) {
            return json_encode($item, JSON_UNESCAPED_SLASHES);
        }, array_keys($this->keys));

        $head = "<?php

namespace CubiStore\\Web\\Cache;

use CubiStore\\Web\\Utils\\ICompiledRoutes;
use Slim\\App;
use Slim\\Routing\\RouteCollectorProxy;

class CompiledRoutes implements ICompiledRoutes {
    function configure(App \$app) {\n";

        $tail = "
    }
    
    function getKeys(): array {
        return [
            " . implode(",\n" . str_repeat(' ', 12), $keys) . "
        ];
    } 
}
";

        $configure = $this->root->compileRoute("\$app", 8);

        return $head . $configure . $tail;
    }
}
