require 'anguilla'

module Spongiae
   module XLIFF
       
       ##
       # Reads all units, but only the translation. 
       def self.read_translations_map(file)
           callback = Xliff_Callback.new(false)
           Anguilla::parse(file,callback)
           return callback.result
       end
       
       ##
       # Reads all units, producing translated bilingual objects 
       def self.read_units(file)
           callback = Xliff_Callback.new(true)
           Anguilla::parse(file,callback)
           return callback.result
       end
       
       
       class Xliff_Callback
           include REXML::StreamListener
           
           def initialize(units)
               @result = {}; @units = units; @multi_file = false
           end
           
           attr_reader :result
           
           def tag_start(element, attributes)
               if element == 'trans-unit' then 
                   @cur_unit = attributes['id']
                   @cur_text = nil
               elsif element == 'file' then 
                   @multi_file = true if @cur_subfile != nil 
                   @cur_subfile = attributes['original']
               elsif (element == 'target') or (element == 'source') 
                   @cur_text = ''
               end
           end
           
           def tag_end(element)
               if element == 'source'
                   @cur_source = @cur_text
               elsif element == 'target'
                   id = @cur_unit; id = "#{@cur_subfile}!!#{id}" if @multi_file
                   if @units then
                      @result[id] = Spongiae::Unit::Bilingual.new @cur_subfile, @cur_unit, {}, @cur_source, @cur_text                        
                   else 
                      @result[id] = @cur_text
                   end
               end
           end
           
           def text(text) 
               if @cur_text != nil then @cur_text = @cur_text + text end
           end
       end
       
   end
end
