<?php
namespace Misuzu\URLs;

use Attribute;
use InvalidArgumentException;
use ReflectionObject;

#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
class URLInfo {
    public function __construct(
        private string $name,
        private string $path,
        private array $query = [],
        private string $fragment = ''
    ) {
        if($path === '')
            throw new InvalidArgumentException('$path may not be empty.');
        if($path[0] !== '/')
            throw new InvalidArgumentException('$path must begin with /.');
    }

    public function getName(): string {
        return $this->name;
    }

    public function getPath(): string {
        return $this->path;
    }

    public function hasQuery(): bool {
        return !empty($this->query);
    }

    public function getQuery(): array {
        return $this->query;
    }

    public function hasFragment(): bool {
        return $this->fragment !== '';
    }

    public function getFragment(): string {
        return $this->fragment;
    }

    public static function handleAttributes(URLRegistry $urls, object $source): void {
        $objectInfo = new ReflectionObject($source);
        $methodInfos = $objectInfo->getMethods();

        foreach($methodInfos as $methodInfo) {
            $attrInfos = $methodInfo->getAttributes(URLInfo::class);
            foreach($attrInfos as $attrInfo)
                $urls->registerInfo($attrInfo->newInstance());
        }
    }
}
