require 'spongiae/unit'
require 'digest/sha1'

module Spongiae
   module Formats
       
       class GettextPo
           
           def initialize(file, props = {})
               @file = file
               if props[:encoding] != nil then @encoding = props[:encoding] else @encoding = 'UTF-8' end
           end
           
           # read_strings : build unit for each string
           # For Plain Text, this is one string per line.
           def read_unit(&sub)
               File.open(@file, "r:#{@encoding}") do |f|
                   src = ''; tra = ''; ctxt = ''; where = ''
                   loop do 
                       line = f.gets
                       if line =~ /^msgctxt "(.+)"/ then ctxt = $1; where = ctxt; end
                       if line =~ /^msgid "(.+)"/ then src = $1; where = src; end
                       if line =~ /^msgstr "(.+)"/ then tra = $1; where = tra; end
                       if line =~ /^"(.+)"/ then where << $1 end
                    
                       if line == nil or line =~ /^\r?\n$/
                            yield Spongiae::Unit::Bilingual.new(@file, Digest::SHA1.hexdigest("#{ctxt}::#{src}"), { "ctxt" => ctxt }, src,tra) 
                            src = ''; tra = ''; ctxt = ''; where = ''
                            break if line == nil
                       end
                   end
               end
           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.traText
                      tra = translations_map[unit.id] if translations_map[unit.id] != nil
                      dest.puts "msgctxt \"#{unit.props['ctxt']}\"" if unit.props['ctxt'] != nil and unit.props['ctxt'].length > 0
                      dest.puts "msgid \"#{unit.srcText}\""
                      dest.puts "msgstr \"#{tra}\""
                      dest.puts ""
                  end
              end
           end
           
       end
       
   end
end
