<?php

declare(strict_types = 1);

// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social.  If not, see <http://www.gnu.org/licenses/>.
// }}}

/**
 * Static wrapper for Symfony's router
 *
 * @package   GNUsocial
 * @category  URL
 *
 * @author    Hugo Sales <hugo@hsal.es>
 * @copyright 2020-2021 Free Software Foundation, Inc http://www.fsf.org
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */

namespace App\Core;

use App\Util\Common;
use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Router as SymfonyRouter;
use Symfony\Component\Routing\RouterInterface;

/**
 * @mixin SymfonyRouter
 */
class Router extends Loader
{
    /**
     * Generates an absolute URL, e.g. "http://example.com/dir/file".
     */
    public const ABSOLUTE_URL = UrlGeneratorInterface::ABSOLUTE_URL;

    /**
     * Generates an absolute path, e.g. "/dir/file".
     */
    public const ABSOLUTE_PATH = UrlGeneratorInterface::ABSOLUTE_PATH;

    /**
     * Generates a relative path based on the current request path, e.g. "../parent-file".
     *
     * @see UrlGenerator::getRelativePath()
     */
    public const RELATIVE_PATH = UrlGeneratorInterface::RELATIVE_PATH;

    /**
     * Generates a network path, e.g. "//example.com/dir/file".
     * Such reference reuses the current scheme but specifies the host.
     */
    public const NETWORK_PATH = UrlGeneratorInterface::NETWORK_PATH;

    public static ?RouterInterface $router = null;

    public static function setRouter(RouterInterface $rtr): void
    {
        self::$router = $rtr;
    }

    public static function isAbsolute(string $url)
    {
        return isset(parse_url($url)['host']);
    }

    /**
     * Generate a URL for route $id with $args replacing the
     * placeholder route values. Extra params are added as query
     * string to the URL
     */
    public static function url(string $id, array $args = [], int $type = self::ABSOLUTE_PATH): string
    {
        if ($type === self::RELATIVE_PATH) {
            Log::debug('Requested relative path which is not an absolute path... just saying...');
        }
        return self::$router->generate($id, $args, $type);
    }

    public static function sanitizeLocalURL(string $url, array $unset_query_args = []): ?string
    {
        try {
            $parts = parse_url($url);
            if ($parts === false || (isset($parts['host']) && $parts['host'] !== Common::config('site', 'server'))) {
                return null;
            }
            self::match($parts['path']);
            if ($unset_query_args !== [] && isset($parts['query'])) {
                $args = [];
                parse_str($parts['query'], $args);
                $args           = array_diff_key($args, $unset_query_args);
                $parts['query'] = http_build_query($args);
            }
            return $parts['path'] . (empty($parts['query']) ? '' : ('?' . $parts['query'])) . (empty($parts['fragment']) ? '' : ('#' . $parts['fragment']));
        } catch (ResourceNotFoundException) {
            return null;
        }
    }

        private RouteCollection $rc;

    /**
     * Route loading entry point, called from `config/routes.php`
     *
     * Must conform to symfony's interface, but the $resource is unused
     * and $type must not be null
     * @param string $resource
     */
    public function load($resource, ?string $type = null): RouteCollection
    {
        $this->rc = new RouteCollection();

        $route_files = glob(INSTALLDIR . '/src/Routes/*.php');
        $to_load     = [];
        foreach ($route_files as $file) {
            require_once $file;
            $ns = '\\App\\Routes\\' . basename($file, '.php');
            if (\defined("{$ns}::LOAD_ORDER")) {
                $to_load[$ns::LOAD_ORDER] = $ns;
            } else {
                $to_load[] = $ns;
            }
        }

        ksort($to_load);
        foreach ($to_load as $ns) {
            $ns::load($this);
        }

        Event::handle('AddRoute', [&$this]);

        // Sort routes so that whichever route has the smallest accept option matches first, as it's more specific
        // This requires a copy, sadly, as it doesn't seem to be possible to modify the collection in-place
        // However, this is fine since this gets cached
        $it = $this->rc->getIterator();
        $it->uasort(fn (Route $left, Route $right) => \count($left->getDefaults()['accept']) <=> \count($right->getDefaults()['accept']));
        $this->rc = new RouteCollection();
        foreach ($it as $id => $route) {
            $this->rc->add($id, $route);
        }

        return $this->rc;
    }

    /**
     * Connect a route to a controller
     *
     * @param string     $id         Route unique id, used to generate urls, for instance
     * @param string     $uri_path   Path, possibly with {param}s
     * @param mixed      $target     Some kind of callable, typically class with `__invoke` or [object, method]
     * @param null|array $param_reqs Array of {param} => regex
     * @param null|array $options    Possible keys are ['condition', 'defaults', 'format',
     *                               'fragment', 'http-methods', 'locale', 'methods', 'schemes', 'accept', 'is_system_path']
     *                               'http-methods' and 'methods' are aliases
     */
    public function connect(string $id, string $uri_path, $target, ?array $options = [], ?array $param_reqs = [])
    {
        // XXX: This hack can definitely be optimised by actually intersecting the arrays,
        // maybe this helps: https://backbeat.tech/blog/symfony-routing-tricks-part-1
        // see: https://symfony.com/index.php/doc/3.1/components/http_foundation.html#accessing-accept-headers-data
        $accept_header_condition = '';
        if (isset($options['accept'])) {
            foreach ($options['accept'] as $accept) {
                $accept_header_condition .= "('{$accept}' in request.getAcceptableContentTypes()) ||";
            }
            $accept_header_condition = mb_substr($accept_header_condition, 0, -3);
        }

        $this->rc->add(
            $id,
            new Route(
                // path -- URI path
                path: $uri_path,
                // defaults = []     -- param default values,
                // and special configuration options
                defaults: array_merge(
                    [
                        '_controller'    => \is_array($target) ? $target : [$target, '__invoke'],
                        '_format'        => $options['format']         ?? 'html',
                        '_fragment'      => $options['fragment']       ?? '',
                        '_locale'        => $options['locale']         ?? 'en',
                        'template'       => $options['template']       ?? '',
                        'accept'         => $options['accept']         ?? [],
                        'is_system_path' => $options['is_system_path'] ?? true,
                    ],
                    $options['defaults'] ?? [],
                ),
                // requirements = [] -- param => regex
                requirements: $param_reqs,
                // options = []      -- possible keys: compiler_class:, utf8
                // No need for a special compiler class for now,
                // Enforce UTF8
                options: ['utf8' => true],
                // host = ''         -- hostname (subdomain, for instance) to match,
                // we don't want this
                host: '',
                // schemes = []      -- URI schemes (https, ftp and such)
                schemes: $options['schemes'] ?? [],
                // methods = []      -- HTTP methods
                methods: $options['http-methods'] ?? $options['methods'] ?? [],
                // condition = ''    -- Symfony condition expression,
                // see https://symfony.com/doc/current/routing.html#matching-expressions
                condition: isset($options['accept']) ? $accept_header_condition : ($options['condition'] ?? ''),
            ),
        );
    }

    /**
     * Whether this loader supports loading this route type
     * Passed the arguments from the `RoutingConfigurator::import` call from
     * `config/routes.php`
     *
     * @codeCoverageIgnore
     */
    public function supports($resource, ?string $type = null): bool
    {
        return 'GNUsocial' === $type;
    }

    /**
     * function match($url) throws Symfony\Component\Routing\Exception\ResourceNotFoundException
     */
    public static function __callStatic(string $name, array $args)
    {
        return self::$router->{$name}(...$args);
    }
}
