
require 'net/http'


class JF_HEADER 

  def initialize(url)

    h = Net::HTTP.new(url.hostname,url.port)
    @head = h.head(url.to_s, nil)
  end

  def mime 
    @head['content-type'].downcase
  end
  def [](k)
    @head[k]
  end
  def show
    @head.each {|key, val| printf "%-14s = %-40.40s\n", key, val }
  end
end


class JF_HTTP

  attr_reader :data, :mime, :url, :header

  def initialize(url)
#$debug.puts "Connect to: #{url.to_s}"
    @url=url
    @host = Net::HTTP.new(url.hostname,url.port)
  end

  def get (headers=nil)
    retrieve { @host.get(@url.to_k,headers) }
  end
  def post (params=nil,headers=nil)
    retrieve { @host.post(@url.to_k,params,headers) }
  end

  def retrieve
    begin
      resp, @data = yield

      @header= resp.to_hash

  #resp.each {|key, val| printf "OK: %-14s = %-40.40s\n", key, val }   

      if not resp['content-location'].nil?
        @url.set_location(resp['content-location'])
      end
      @mime = resp['content-type'].downcase

    rescue Net::ProtoRetriableError => detail

      head = detail.data

      if head.code == "301" or head.code == "302"

        @url.set_location(head['location'])
     #   h.finish
       # puts "RETRY  #{@url.to_s}"
        retry
      else
#head.each {|key, val| printf ("Error %d: %-14s = %s\n",head.code, key, val) }  
        raise 
      end
    rescue  Net::SocketError => detail
     # $stderr.puts "Error Socket #{@url.to_s}"
     # $stderr.puts  detail
      raise BadUrl.new("Socket error #{@url.to_s}\n#{detail}" )

    rescue Net::ProtocolError => detail
      head = detail.data
     # $stderr.puts "Error #{head.code}: #{head.message} #{@url.to_s}"
# head.each {|key, val| printf " %-14s = %-40.40s\n", key, val }
      raise BadUrl.new("Protocol error #{head.code}:\n#{head.message}\n#{@url.to_s}")
#		ensure
#		 h.finish
    end
  end

end
