<?php
namespace IntellexApps\PHP\UploadFile\Routing;

use IntellexApps\PHP\UploadFile\Network\Request;
use IntellexApps\PHP\UploadFile\Network\Response;

class Router
{

    /** @var null Request */
    private static $request     = null;
    
    /** @var null Response */
    private static $response    = null;

    /** @var [] */
    private static $overridenRoutes = [];

    /** @var [] */
    private static $prefixes = [];

    /**
     * Set request
     *
     * @param $request
     */
    public static function setRequest(Request $request)
    {
        self::$request = $request;
    }

    /**
     * Set response
     *
     * @param $response
     */
    public static function setResponse(Response $response)
    {
        self::$response = $response;
    }

    /**
     * Get request
     *
     * @return Request
     */
    public static function getRequest()
    {
        return self::$request;
    }

    /**
     * Get response
     *
     * @return Response
     */
    public static function getResponse()
    {
        return self::$response;
    }

    /**
     * Build route
     */
    public static function getRouteParts()
    {
        $path = self::getPath();

        if(isset(self::$overridenRoutes[$path])) {
            $path = self::$overridenRoutes[$path];
        }

        foreach(self::$prefixes as $prefix => $callable) {
            if(strpos($path, $prefix) === 0) {
                $data = $callable();
                self::$request->set('route_params', $data);
                $path = substr($path, strlen($prefix));
                break;
            }
        }

        if(isset(self::$overridenRoutes[$path])) {
            $path = self::$overridenRoutes[$path];
        }

        return array_values(array_filter(explode('/', $path)));
    }

    /**
     * Get path
     *
     * @return mixed
     */
    private static function getPath()
    {

        if(isset($_GET['url'])) {
            return $_GET['url'];
        }
        if(isset($_GET['request'])) {
            return $_GET['request'];
        }

        if(isset($_SERVER['REQUEST_URI'])) {
            if(strpos($_SERVER['REQUEST_URI'], $_SERVER['SCRIPT_NAME']) == 0) {
                $url = substr($_SERVER['REQUEST_URI'], strlen($_SERVER['SCRIPT_NAME']));
            } else {
                $url = $_SERVER['REQUEST_URI'];
            }
            return explode('?', $url)[0];
        }

    }

    /**
     * Configure routes
     *
     * @param $param
     */
    public static function configureRoutes($param)
    {
        if($param['routes']) {
            self::$overridenRoutes = $param['routes'];
        }

        if($param['prefixes']) {
            self::$prefixes = $param['prefixes'];
        }
    }
}