require 'spongiae/unit'

module Spongiae
   module Formats
       
       class JavaProperties
           
           def initialize(file, props = {})
               @file = file
           end
           
           # read_strings : build unit for each string
           # Convert from native2ascii, and treat multi-line entries
           def read_unit(&sub)
               File.open(@file, "r:#{@encoding}") do |f|
                   while line = f.gets
                       if line =~ /(.+)\s*=\s*(.+)\r?\n/ then
                           key = decode($1); val = decode($2)
                           while val =~ /\\[\s*\r\n]*$/
                             val.sub! /\\[\s*\r\n]*$/, ''
                             val = val + f.gets.gsub(/^\s+/,'')
                           end
                           val.sub! /[\s*\r\n]*$/, ''
                           yield Spongiae::Unit::Unilingual.new(@file, key, nil, val)
                       end
                   end
               end
           end
           
           def decode(v)
               return v.gsub(/\\n/, "\n").gsub(/\\u([0-9A-Fa-f]{4})/) { [Regexp.last_match[1].to_i(16)].pack('U') }
           end  
           
           def translate(dest_file_name,translations_map,props={})
              File.open(dest_file_name, 'w:UTF-8') do |dest|
                  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 "#{unit.id} = #{tra.gsub(/\n/, "\\n\\\n    ").gsub(/[\u0080-\uFFFF]/,"\\u" + $0.ord.to_s(16).rjust(4,"0"))}"
                      end
                  end
              end
           end
       end
       
   end
end
 
