require 'spongiae/unit'

require 'anguilla'

module Spongiae
   module Formats
       
       class AndroidCallbacks
           include REXML::StreamListener
           
           def initialize(sub)
               @sub = sub
           end
           
           def tag_start(element, attributes)
               if element == 'string'
                   @id = attributes['name']
                   @text = ''
               end	
           end
           
           def tag_end(element)
               if element == 'string' then 
                   @sub.call Spongiae::Unit::Unilingual.new(@file, @id, nil, @text)
                   @id = nil; @text = ''
               end
           end
           
           def text(text) 
               if @id != nil then @text = @text + text end
           end
       end
       
       
       class AndroidStrings
           
           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)
               callback = AndroidCallbacks.new(sub)
               Anguilla::parse(@file,callback)
           end
           
           def translate(dest_file_name,translations_map,props={})
              File.open(dest_file_name, 'w:UTF-8') do |dest|
                  dest.puts <<'EOF'
<?xml version="1.0" encoding="UTF-8" ?>
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
EOF

                  read_unit do |unit|
                      tra = unit.text
                      if translations_map[unit.id] != nil or props['--all'] != nil then                          
                         tra = translations_map[unit.id] if translations_map[unit.id] != nil
                         dest.puts "	<string name='#{unit.id}'>#{tra.encode(:xml => :text)}</string>"
                      end
                  end
                  dest.puts "</resources>"
              end
           end
           
       end
       
   end
end
