#
# uri.rb -- URI class
#
# Author: IPR -- Internet Programming with Ruby -- writers
# Copyright (C) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou
#
# $IPR: uri.rb,v 1.6 2002/02/05 20:20:32 gotoyuzo Exp $

begin
  require 'uri'
rescue LoadError
  $stderr.puts "URI not found; using WEBrick::URI ..."

module WEBrick

  class URI
    class InvalidURIError< StandardError; end

    # From RFC2396
    #  Appendix B. Parsing URI Reference with a Regular Expression
    #
    #  The following line is the regular expression
    #  for breaking-down a URI reference into its components.
    #
    #   ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
    #    12            3  4          5       6  7        8 9
    # ==
    #     scheme    = $2
    #     authority = $4
    #     path      = $5
    #     query     = $7
    #     fragment  = $9

    attr_accessor :scheme, :host, :port, :path, :query

    def initialize(s)
      @str = s.dup
      if %r!^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?! =~ s
        @scheme    = $2
        @authority = $4
        @path      = $5
        @query     = $7
        @fragment  = $9
        if /:(\d+)$/ =~ @authority
          @host, @port = $`, $1.to_i
        else
          @host = @authority
          @port = nil
        end
      else
        raise InvalidURIError, "bad URI(is not URI?) #{s}"
      end
    end

    def to_s
      uri = ""
      uri << "#{@scheme}://#{@host}" if @scheme
      uri << ":#{@port}"   if @port
      uri << @path
      uri << "?#{@query}"  if @query
      uri
    end

    def inspect
      "#<%s:0x%x URL:%s>" % [ type, id, to_s ]
    end

    def URI.parse(s)
      new(s)
    end
  end

end

end
