<?php

namespace Snaju\Inception\Event\Types;

use Snaju\Inception\Event\Event;
use Snaju\Inception\Exception\Exception;
use Snaju\Inception\InceptionCore;
use Snaju\Inception\Request\WebRequest;
use Snaju\Inception\Route\Loaders\Twig\TemplateManager;
use Snaju\Inception\Route\Route;
use Snaju\Inception\Route\RouteManager;
use Snaju\Inception\Route\RouteMiddleware;
use Snaju\Inception\Route\RouteNode;

// TODO: add docs
class OnRouteEvent extends Event
{

    private string $path;

    /**
     * OnRouteEvent constructor.
     * @param string $path
     */
    public function __construct(string $path)
    {
        $this->path = $path;
    }

    public function run(Event $event): Event
    {
        return $this;
    }

    public function onEnd(Event $event)
    {
        try {
            // Do the default routing here.
            if ($event instanceof OnRouteEvent) {
                $node = &RouteManager::findRoute($event->getPath());
                if ($node instanceof Route) {

                    // Execute any middleware attached to the route
//                foreach ($node->getMiddleware() as $middleware) {
//                    $a = call_user_func($middleware->getFunc(), InceptionCore::getRequest(), $node);
//                    if (is_array($a)) {
//                        // A array was returned so set in the TemplateManager
//                        $node->data = array_merge($node->data, $a);
////                            TemplateManager::merge($a);
//                    }
//                }

                    foreach ($node->getFiles() as $routeFile) {
                        require $routeFile;
                    }

                    TemplateManager::merge($node->data);
                    InceptionCore::getRequest()->mergeAttributes($node->data);

                    // A valid route was found
                    $node->onCall(InceptionCore::getRequest());
                } else {
                    throw new \Exception("No Route Found for " . $event->getPath());
                }
            } else {
                throw new \Exception("Invalid type of event passed into OnRouteEvent.");
            }
        } catch (Exception $e) {
            (new OnNoRouteFoundEvent($e))->call();
        }

        return $event;
    }

    /**
     * @return mixed|string
     */
    public function getPath(): string
    {
        return $this->path;
    }


}