require 'web/htmlparser'

class TkHtml

  def initialize(adr)

    @top=GoWindow.new(self)

    @menubar=Menu.new
    @menubar.add('command','label'=>'Back','command'=>proc {go_back})
    @menubar.add('command','label'=>'Next','command'=>proc {go_forw})
    @menubar.add('command','label'=>'Close','command'=>proc {@top.destroy})

    @top.configure('menu'=> @menubar)

    frame= TkFrame.new(@top).pack('fill'=>'both','expand'=>'yes')
    @text=TkText.new(frame).pack('side' => 'left','fill'=>'both','expand'=>'yes')
    sc=TkScrollbar.new(frame, 'command' => proc { |*args| @text.yview *args} ).pack( 
                                                                                    'side' => 'right',
                                                                                    'fill' => 'y')


    @text.yscrollcommand(proc { |*args| sc.set( *args) })
    @text.configure('bg'=>'white','wrap'=>'word','padx'=>10)
    @text.configure('font'=>'times 10')

    @link_var=TkVariable.new
    @label=TkLabel.new(@top,'textvariable'=>@link_var).pack('expand'=>'no','fill'=>'x')


#buf=''
#File.open(ARGV[0]){  |f| buf=f.read}
#buf.tr!("\r\n",'')

    @list_url=[JF_URL.new(adr)]
    @c_index=0
    display()

  end

  def go_back
    if @c_index>0
      @c_index -=1 
      display()
    end
  end

  def go_forw
    if @c_index < @list_url.length-1
      @c_index +=1
      display()
    end
  end


  def display(adr=nil)

    if adr
      url=@list_url[@c_index].relative(adr)
      for i in @c_index+1...@list_url.length
        @list_url.delete_at(i)
      end
      @list_url.push(url)
      @c_index+=1
    else
      url=@list_url[@c_index]
    end

    @text.cursor('watch')
    Tk.update

    @text.configure('state'=>'normal')
    @text.delete(1.0,'end')
    begin
      @page= JF_HTML.new(url)
      parser=HTMLParser.new(@page,@text,@link_var) { |adr| display(adr) }
    rescue
      @text.insert('end',$!)
    ensure
      @text.configure('state'=>'disabled')
      @text.cursor('')
    end
  end



end
