require 'spongiae/unit'

module Spongiae
   module Formats
       
       class Srt
           
           def initialize(file, props = {})
               @file = file
               if props[:encoding] != nil then @encoding = props[:encoding] else @encoding = 'UTF-8' end
           end
           
           def read_unit(&sub)
               File.open(@file, "r:#{@encoding}") do |f|
                   id = ''; text = ''; pstart = ''; pend = ''
                   while line = f.gets
                       id = line.gsub(/\r?\n$/,'')
                       
                       # timestamps
                       line = f.gets
                       pstart = $1 if line =~ /^([\d:,]+)\s-->/
                       pend = $1 if line =~ /-->\s([\d:,]+)/
                       
                       loop do
                           line = f.gets
                           break if line == nil or line =~ /^\r?\n$/
                           text << line
                       end
                       text.gsub!(/\r?\n$/,'') 
                                        
                       yield Spongiae::Unit::Unilingual.new(@file, id, { "start" => pstart, "end" => pend }, text)
                       id = ''; text = ''; pstart = ''; pend = ''
                   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.text
                      tra = translations_map[unit.id] if translations_map[unit.id] != nil
                      dest.puts unit.id
                      dest.puts "#{unit.props['start']} --> #{unit.props['end']}"
                      dest.puts tra
                      dest.puts ""
                  end
              end
           end
           
       end
       
   end
end
