require 'spongiae/unit'

require 'nokogiri'
require 'zip'

module Spongiae
   module Formats
       
       class OpenXmlCallbacks < Nokogiri::XML::SAX::Document
           
           def initialize(file,sub)
               @sub = sub; @file = file; @id = 0; @text = ''
           end
           
           def start_element(name, attrs = []) start_element_namespace(name,attrs) end
               
           def start_element_namespace(name, attrs = [], prefix = nil, uri = nil, ns = [])
               @id = @id + 1 if name == 'p' and prefix == 'w'
           end
           
           def end_element_namespace(name, prefix = nil, uri = nil)
               if name == 'p' and prefix == 'w' then 
                   @sub.call Spongiae::Unit::Unilingual.new(@file, @id.to_s, nil, @text)
                   @text = ''
               end
           end
           
           def characters(text) 
               if @id != nil then @text = @text + text end
           end
       end
       
       class OpenXmlFile
           
           def initialize(file, props = {})
               @file = file
           end
           
           # read_strings : build unit for each string
           # For Plain Text, this is one string per line.
           def read_unit(&sub)
               Zip::File.foreach(@file) do |entry|
                    if entry.name =~ /(document\d?|footnotes?)\.xml/ then                       
                        callback = OpenXmlCallbacks.new(entry.name,sub)
                        parser = Nokogiri::XML::SAX::Parser.new(callback)
                        parser.parse(entry.get_input_stream)
                    end
               end
           end
           
           def translate(dest_file_name,translations_map,props={})
               raise "Format OpenXML does not support translation for the moment"                   
           end
           
       end
       
   end
end
