<?php
namespace Bitrix\Main\Web;

use \Bitrix\Main\IO;

class Uri
{
	protected $uri;
	protected $uriType;

	protected static $directoryIndex = "index.php";

	public function __construct($uri, $uriType)
	{
		if ($uriType < UriType::Unknown || $uriType > UriType::Relative)
			throw new \Bitrix\Main\ArgumentTypeException("uriType", UriType::getTypeNamesArray());

		if ($uri == null)
			$uri = "";

		$this->uri = $uri;
		$this->uriType = $uriType;
	}

	public function parse($uriPart = -1)
	{
		return parse_url($this->uri, $uriPart);
	}

	public function convertToPath()
	{
		if ($this->uriType != UriType::Relative)
		{
			$path = $this->parse(UriPart::Path);
		}
		else
		{
			$path = $this->uri;
			$p = strpos($path, "?");
			if ($p !== false)
				$path = substr($path, 0, $p);
		}

		if (substr($path, -1, 1) === "/")
			$path = self::addDirectoryIndex($path);

		$path = IO\Path::Normalize($path);

		if (IO\Path::Validate($path))
			return $path;

		throw new \Bitrix\Main\SystemException("Uri is not valid");
	}

	public static function addDirectoryIndex($dir)
	{
		if (!is_string($dir))
			throw new \Bitrix\Main\ArgumentTypeException("dir", "string");

		$dir = rtrim($dir, "/");

		return $dir."/".self::$directoryIndex;
	}
}

class UriType
{
	const Unknown = 0;
	const Absolute = 1;
	const Relative = 2;

	public static function getTypeNamesArray()
	{
		return array("UriType.Unknown", "UriType.Absolute", "UriType.Relative");
	}
}

class UriPart
{
	const All = -1;
	const Scheme = PHP_URL_SCHEME;
	const Host = PHP_URL_HOST;
	const Port = PHP_URL_PORT;
	const User = PHP_URL_USER;
	const Password = PHP_URL_PASS;
	const Path = PHP_URL_PATH;
	const Query = PHP_URL_QUERY;
	const Fragment = PHP_URL_FRAGMENT;
}