=begin
  parser/glade.rb - parser for Glade-2

  Copyright (C) 2004  Masao Mutoh
 
  You may redistribute it and/or modify it under the same
  license terms as Ruby.
=end

require 'cgi'

module GetText
  module GladeParser

    TARGET1 = /<property.*translatable="yes">(.*)/
    TARGET2 = /(.*)<\/property>/

    module_function
    def parse(files, targets = [])
      @targets = targets
      files.each do |file|
        lines = IO.readlines(file)
        parse_lines(file, lines)
      end
      @targets
    end

    #from ary of lines.
    def parse_lines(file, lines)
      cnt = 0
      target = false
      line_no = 0
      val = nil
      
      loop do 
        line = lines.shift
        break unless line
        
        cnt += 1
        if TARGET1 =~ line
          line_no = cnt
          val = $1 + "\n"
          target = true
          if TARGET2 =~ $1
            val = $1
            add_target(val, file, line_no)
            val = nil
            target = false
          end
        elsif target
          if TARGET2 =~ line
            val << $1
            add_target(val, file, line_no)
            val = nil
            target = false
          else
            val << line
          end
        end
      end
      @targets
    end

    def add_target(val, file, line_no)
      return unless val.size > 0
      assoc_data = @targets.assoc(val)
      val = CGI.unescapeHTML(val)
      if assoc_data 
        @targets[@targets.index(assoc_data)] = assoc_data << "#{file}:#{line_no}"
      else
        @targets << [val.gsub(/\n/, '\n'), "#{file}:#{line_no}"]
      end
    end
  end
end

if __FILE__ == $0
  # ex) ruby glade.rb foo.glade  bar.glade
  p GetText::GladeParser.parse(ARGV)
end
