<?php

use WhiteLeaf\Common\Application;
use WhiteLeaf\Common\ControllerAnnotationLoader;
use WhiteLeaf\Common\DirectoryClassIterator;
use WhiteLeaf\Common\Log;
use WhiteLeaf\Common\Routing\Route;
use WhiteLeaf\Common\Routing\Router;
use WhiteLeaf\Common\Session\SessionCredentials;
use WhiteLeaf\Common\Session\SessionInstance;
use WhiteLeaf\Common\Session\Cookie;
use WhiteLeaf\Common\Config;
use WhiteLeaf\Common\Authentication\AuthenticationService;
use WhiteLeaf\Common\Request;
use WhiteLeaf\Common\Utils\Http;
use Doctrine\Common\Annotations\AnnotationReader;

ini_set('session.gc_maxlifetime', 5 * 60 * 60);

require __DIR__ . '/../lib/boot.app.php';
$app = Application::instance();

try {
    // Routing
    $router = new Router();
    ControllerAnnotationLoader::factory(
        new DirectoryClassIterator (_BASEDIR . '/lib/', 'WhiteLeaf/Controllers/'),
        new Doctrine\Common\Annotations\CachedReader(new AnnotationReader(), Application::getVerCache()),
        $router
    );

    // Config.links routes
    foreach (Config::$s['build']['links'] as $path => $url) {
        $router->addRoute(new Route(['path' => $path, 'url' => $url]));
    }
    $app->setRouter($router);

    // Setup user session
    $session = new SessionInstance();
    $session->setSessionCookie(new Cookie('sid', Config::$a['cookie']));
    $session->setRememberMeCookie(new Cookie('rememberme', Config::$a['cookie']));
    $session->setCredentials(new SessionCredentials());
    $app->setSession($session);
    AuthenticationService::instance()->startSession();

    // Attempts to find a route and execute it
    $app->executeRequest(new Request([
        'uri' => $_SERVER['REQUEST_URI'],
        'method' => $_SERVER['REQUEST_METHOD'],
        'headers' => Http::extractHeaders($_SERVER),
        'ipAddress' => Http::extractIpAddress($_SERVER),
        'get' => $_GET,
        'post' => $_POST
    ]));
} catch (Exception $e) {
    Log::error($e->getMessage());
    echo "Application failed to start. Check the error logs for more info.";
}