# $Id: ext_diff.rb,v 1.1 2004/05/12 18:26:04 eto Exp $
# Copyright (C) 2003-2004 Kouichirou Eto, All rights reserved.
# This is free software with ABSOLUTELY NO WARRANTY.
# You can redistribute it and/or modify it under the terms of the GNU GPL2.

require "qwik/diff"
require "qwik/util"
require "qwik/qxml"

module Qwik
  class DiffHtmlGenerator
    def initialize(s1, s2)
      @s1 = s1.gsub(/\r/, "")
      @s2 = s2.gsub(/\r/, "")
      @g = Qxml.new
    end

    def to_txt
      a1 = @s1.split("\n").collect! {|s| "#{s}\n"}
      a2 = @s2.split("\n").collect! {|s| "#{s}\n"}
      Diff.diff(a1, a2) 
    end

    def to_rexml
      e = @g.div
      src = @s1.split("\n").collect {|s| "#{s.escapeHTML}" }
      si = 0
      di = 0
      to_txt().each {|action, position, elements|
        case action
        when :-
          while si < position
	    e << REXML::Text.new(src[si])
	    e << @g.br
            si += 1
            di += 1
          end
          si += elements.length
          elements.each {|l|
            e << @g.del{l.chomp}
	    e << @g.br
	  }
        when :+
          while di < position
	    e << REXML::Text.new(src[si])
	    e << @g.br
            si += 1
            di += 1
          end
          di += elements.length
          elements.each {|l|
            e << @g.ins{l.chomp}
	    e << @g.br
	  }
        end
      }
      while si < src.length
	e << REXML::Text.new(src[si])
	e << @g.br
        si += 1
      end
      e
    end
  end
end
