require 'web/JFhttp'
require 'English'
require 'web/JFparser'
require 'web/tkhtml'

class BadUrl < ArgumentError
end

class JF_HTML 
  attr_reader :data, :url, :base, :mime

  def initialize(url)
    @url=url

    if url.http?
      connect = JF_HTTP.new(url)
      connect.get
      @data = connect.data
      @mime = connect.mime

    elsif url.file?
      begin
        File.open(url.path,'r') { |f|  @data = f.read }
      rescue Exception => detail
        raise BadUrl.new( detail.to_s)
      end
    elsif url.ftp?
      raise( BadUrl,'ftp not implemented yet !!')
    else
      raise(BadUrl,url.to_s) 
    end
#        @data.delete!("\r\n")
    @parser=JF_PARSER.new
    @parser.feed(@data)
    @parser.close

    @base = find_base
#	$debug.puts "page avec base: #{@base} (#{url.to_s})" unless @base.nil?
    del_base!
  end	

  def sub_a! 
    @data.gsub!(/(< *a.*?href *= *" *)([^"]+)("[^>]*>)/im ) { $1+ yield($2) +$3}
  end

  def sub_frame!
    @data.gsub!( /(< *frame.*?src *= *" *)([^"]+)("[^>]*>)/im ){$1+ yield($2)+ $3}
  end
  def sub_img!
    @data.gsub!( /(< *img.*?src *= *" *)([^"]+)("[^>]*>)/im ){$1+ yield($2)+ $3}
  end

  def find_base
    @data =~ /(< *base.*?href *= *" *)([^"]+)("[^>]*>)/im and  $2
  end

  def sub_base!
    @data.sub!( /(< *base.*?href *= *" *)([^"]+)("[^>]*>)/im ){ $1+ yield($2) +$3}
  end

  def del_base!
    @data.sub!( /(< *base.*?href *= *" *)([^"]+)("[^>]*>)/im ){ ''}
  end

  def scan_a
    @data.scan(/< *a *href *= *['"]([^'"]+)['"]/im) { yield $1 }
  end

  def each_item
    @data.split(/[<>]/).each { |line| yield line }
  end

  def store(pathname)
      #    $debug.puts "store: #{@url.to_s} -> #{pathname}"
    File.open(pathname, 'w') { |file| 
      file.print @data
    }
  end

  def links
    @parser.links
  end

  def frames
    @parser.frames
  end


end

class JF_POST < JF_HTML

  def initialize(url,params=nil,headers=nil)
    if headers == nil
      headers={'Content-type'=>'application/x-www-form-urlencoded'}
    end

    str_params = ''
    unless params.nil?
      params.each_pair {|k,v| str_params << k << '=' << v << '&'}
      str_params[-1]=''
    end
    connect = JF_HTTP.new(url)
    connect.post(str_params,headers)
    @data = connect.data
    @data.delete!("\r\n")
    #	@parser=JF_PARSER.new(@data)
    @base = find_base
#	$debug.puts "page avec base: #{@base} (#{url.to_s})" unless @base.nil?
    del_base!
    @mime = connect.mime

  end

end

