require 'spongiae/unit'

module Spongiae
   module Formats
       
       class PlainText
           
           def initialize(file, props = {})
               @file = file
               if props[:encoding] != nil then @encoding = props[:encoding] else @encoding = 'UTF-8' end
               case props['end-para'] 
                  when /bl/i then @endPara = "\n\n"     # blank line
                  when /nl/i then @endPara = "\n"       # new line,
                  when /none/i then @endPara = nil      # entire buffer 
                  else @endPara = $/
               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|
                   i = 0
                   while line = f.gets(@endPara)
                       i = i + 1
                       line.gsub! /\r?\n/, ' '
                       yield Spongiae::Unit::Unilingual.new(@file, i.to_s, nil, line) if line =~ /./
                   end
               end
           end
           
           def translate(dest_file_name,translations_map,props={})
              File.open(dest_file_name, 'w:UTF-8') do |dest|
                   File.open(@file, "r:#{@encoding}") do |ori|
                       i = 0
                       while line = ori.gets(@endPara)
                           i = i + 1
                           if line =~ /./ then
                              line = translations_map[i.to_s] if translations_map[i.to_s] != nil
                           end
                           line.gsub! /\r?\n/, ''   # because puts will add a new line
                           dest.puts line
                       end
                   end
              end
           end
           
       end
       
   end
end
