require "tempfile"

class TextMark<TkObject
  def initialize(parent, index,name)
    if not parent.kind_of?(TkText)
      fail format("%s need to be TkText", parent.inspect)
    end
    @t = parent
    @path = @id = name
    tk_call @t.path, 'mark', 'set', @id, index
    @t._addtag id, self
  end

end

class HTMLParser < SGMLParser

  def initialize(page,w,label,&action)
    super(true)

    @page=page
    @action=action
    @link_var=label

    @link_var.value=@page.url.to_s

    @tempfile=Tempfile.new('gif_image').path


=begin
    italic=TkFont.new('slant'=>'italic')
    bold=TkFont.new('weight'=>'bold')

    h1=TkFont.new('size'=>20,'weight'=>'bold')
    h2=TkFont.new('size'=>16,'weight'=>'bold')
    h3=TkFont.new('size'=>12,'weight'=>'bold')
    h4=TkFont.new('size'=>8,'weight'=>'bold')
=end

    @display=w
    @display.tag_configure('unknown','foreground','green')
    @display.tag_configure('known','foreground','brown')
    @display.tag_configure('a','foreground'=>'blue','underline'=>'true')
    @display.tag_configure('i','font'=>'times 10 italic')
    @display.tag_configure('b','font'=>'times 10 bold')
    @display.tag_configure('u','underline'=>'true')
    @display.tag_configure('cnt','justify','center')
    @display.tag_configure('list','lmargin1'=>30,'lmargin2'=>40)
    @display.tag_configure('blockquote','lmargin1'=>20,'lmargin2'=>10)
    @display.tag_configure('pre','font'=>'fixed')
    @display.tag_configure('H1','font'=>'times 20 bold')
    @display.tag_configure('H2','font'=>'times 16 bold')
    @display.tag_configure('H3','font'=>'times 12 bold')
    @display.tag_configure('H4','font'=>'times 8 bold')



    @display.bind('Enter','')
    @display.tag_bind('a','Enter',proc {enter_link} )
    @display.tag_bind('a','Leave',proc {leave_link} )

    @display.bind('ButtonPress-1',proc { follow_link })

    @c_tag=[]
    @marks={}
    @body=false
    @pre_formatted=false

    @buf=''
    feed(@page.data)
    close

    set_view(@page.url.fragment)	if @page.url.fragment

  end

  def enter_link
    @display.cursor('hand2')
    @link_var.value= find_link
  end

  def leave_link
    @display.cursor('')
    @link_var.value=@page.url.to_s
  end

  def find_link
    link=nil
    tags= @display.tag_names('current')
    if tags.include?('a')

      tags.each { |l| if l =~ /rubygo_html_(.*)/
        link=$1
        break
    end }
  end
  link
  end

  def follow_link
    if link= find_link
      @action.call(link)
    end
  end

  def dbg(tag)
  #	@display.insert('end',"<#{tag}>",'unknown')
  end
  def db(tag)
  #	@display.insert('end',"<#{tag}>",'known')
  end

  def start_img(attrs)
    if src= attrs.assoc('src')
      path=src[1].tr('"','')
      if path =~ /\.gif$/
        begin
          url= @page.url.relative(path)
          if url.http?
            img= JF_HTML.new(url)
            img.store(@tempfile)
  ##
  ## voir module TEMPFILE
  ##
            image=TkPhotoImage.new('file'=>@tempfile )

          elsif url.file?

            image= TkPhotoImage.new('file'=>url.path)
          end

          TkTextImage.new(@display,'end','image'=> image)
  #img.data.gsub!('}','\}')
  #$ip._eval("image create photo gif_img -data {#{img.data}}")
  #$ip._eval("#{@display.path} image create end -image gif_img")
        rescue
          return
        end

      end
    end
  end

  def handle_data(data)
    return unless @body
    unless @pre_formatted
  #data.strip!
      data.chomp!("\n")
      return if data.empty?
      data.tr!("\n"," ")
      data.squeeze!(' ')

    end
    @display.insert('end',data,@c_tag)
  end

  def handle_starttag(tag, method, attrs)
    db(tag)
    super(tag, method, attrs)
  end


  def handle_endtag(tag, method)
    super(tag, method)
    db("/#{tag}")
  end

  def handle_special(data)
  #puts "special: #{data}"
  end
  def handle_comment(data)

  #puts "comment: #{data}"
  end


  def start_a(attrs)
    @c_tag.push('a')
    if href=attrs.assoc('href')
      addr= href[1].gsub(/"|'/,'').strip
      @c_tag.push('rubygo_html_'+addr)
    else
      @c_tag.push('')
    end

    if name= attrs.assoc('name')
      anchor=name[1].gsub(/"|'/,'').strip
      set_mark(anchor)
    end

  end

  def set_mark(name)
  #debug  "#{name},#{@display.index(idx)}"
  #  $ip._eval("#{@display.path} mark set #{name} #{idx}")
  #  $ip._eval("#{@display.path} insert  #{name}  #{name} known")
    @marks[name]=@display.index('end')
  end

  def set_view(mark)
  # @display.yview('120.0')
    $ip._eval("#{@display.path} yview #{@marks[mark]}")
  end

  def end_a
    @c_tag.pop
    @c_tag.pop
  end

  def start_b(attrs)
    @c_tag.push('b')

  end
  def end_b
    @c_tag.pop

  end

  def start_center(attrs)
    @display.insert('end',"\n")
    @start_center=@display.index('insert')
  end
  def end_center

    stop=@display.index('insert')
    @display.tag_add('cnt',@start_center,stop)
    @display.insert('end',"\n")
  end

  def start_ul(attrs)
    @display.insert('end',"\n")
    @start_ul=@display.index('insert')
  end

  def end_ul

    stop=@display.index('insert')
    @display.tag_add('list',@start_ul,stop)
    @display.insert('end',"\n")
  end
  def start_ol(attrs)
    @display.insert('end',"\n")
    @start_ul=@display.index('insert')
    @ol_index=0
  end

  def end_ol
    stop=@display.index('insert')
    @display.tag_add('list',@start_ul,stop)
    @display.insert('end',"\n")
    @ol_index=nil
  end

  def start_pre(attrs)
    @pre_formatted=true
    @display.insert('end',"\n")
    @c_tag.push('pre')
  end
  def end_pre
    @pre_formatted=false
    @c_tag.pop
    @display.insert('end',"\n")
  end
  def start_br(attrs)
    @display.insert('end',"\n")
  end

  def start_p(attrs)
    @display.insert('end',"\n")
  end
  def end_p
    @display.insert('end',"\n")
  end

  def start_i(attrs)
    @c_tag.push('i')
  end

  def end_i
    @c_tag.pop
  end

  def start_u(attrs)
    @c_tag.push('u')
  end

  def end_u
    @c_tag.pop
  end

  def start_body(attrs)
    @body=true
  end
  def end_body
    @body=false
  end
  def start_head(attrs)
    @head=true
  end
  def end_head
    @head=false
  end

  def start_html(attrs)
    @html=true
  end

  def feed(data)
    super(data)
    unless @html
      @display.insert('end',data)

    end
  end



  def start_hr(attrs)
    @display.insert('end',"\n _____\n",'cnt')
  end


  def start_li(attrs)
    if @ol_index
      @ol_index+= 1
      @display.insert('end',"\n#@ol_index. ")
    else
      @display.insert('end',"\n. ")
    end
  end

  def end_li
  end

  def start_h1(attrs)
    @c_tag.push('H1')
  end
  def end_h1
    @display.insert('end',"\n")
    @c_tag.pop
  end
  def start_h2(attrs)
    @c_tag.push('H2')
  end
  def end_h2
    @display.insert('end',"\n")
    @c_tag.pop
  end
  def start_h3(attrs)
    @c_tag.push('H3')
  end
  def end_h3
    @display.insert('end',"\n")
    @c_tag.pop
  end
  def start_h4(attrs)
    @display.insert('end',"\n")
    @c_tag.push('H4')
  end
  def end_h4
    @display.insert('end',"\n")
    @c_tag.pop
  end

  def start_blockquote(attrs)
    @c_tag.push('blockquote')
  end
  def end_blockquote
    @c_tag.pop
  end


  def unknown_starttag(tag,attrs)
    dbg(tag)
  end
  def unknown_endtag(tag)
    dbg("/#{tag}")
  end


end


