require 'lib/irb-locale'

module SimpleI18N

  def self.Message
    SimpleI18N::Message.instance
  end

  def self.Locale
    SimpleI18N::Locale.instance
  end

  def self.windows?
    if /mswin/ =~ PLATFORM
      return true
    elsif /djpp/ =~ PLATFORM
      return true
    else
      false
    end
  end

  class Locale

    if Locale.method_defined?(:initialize)
      undef initialize
    end

    def self.get_locale(lang = nil)
      if lang.nil? and SimpleI18N.windows?
	if  Module.constants.include?('Win')
	  if Phi::LANG == 17
	    lang = "ja_JP.SJIS"
	  end
	end
      end
      IRB::Locale.new(lang)
    end

    def self.instance
      @locale
    end

    if @locale.nil?
      @locale = get_locale
      #@locale = get_locale('ja_JP.eucJP')
      #@locale = get_locale('C')
    end

  end

  class Message

    if @msg.nil?
      @locale = nil
      @msg = {}
    end

    if Message.method_defined?(:initialize)
      undef initialize
    end

    def self.instance
      @msg
    end

    def self.set_locale(locale)
      @locale = locale
    end

    def self.set_message(filename)
      path = @locale.find(filename)
      if path.nil?
	$stderr.print "Locale#find\n"
	$stderr.print "#{filename}: File Not Found\n"
	exit
      else
	f = File::open(path)
      end

      i = 0
      begin
	arr = f.readlines
      ensure
	f.close
      end
      
      arr.each do |l|
	i += 1
	while l != ''
	  if /^\s*$/ =~ l
	    break
	  end
	  unless /=/ =~ l 
	    unless /#/ =~ l
	      $stderr.print "#{path} line #{i}: '=' is not found.\n"
	      break
	    end
	  end

	  case l
	  when /^(.*?)#.*/
	    l = $1
	  when /^([^#]*?)=([^#]*)/
	    key = $1.strip
	    value = $2.strip
	    if key == ''
	      $stderr.print "#{path} line #{i}: Key is empty.\n"
	    elsif value == ''
	      $stderr.print "#{path} line #{i}: Value is empty.\n"
	    elsif @msg.keys.include?(key)
	      $stderr.print "#{path} line #{i}: The same key(#{key}) is used.\n"
	    else
	      @msg[ @locale.String($1.strip) ] = @locale.String($2.strip)
	    end
	    l = ''
	  when /^./
	    l = $'
	  end
	end
      end

    end

    def @msg.set_message(filename)
      Message.set_message(filename)
    end

    if @locale.nil?
      set_locale(SimpleI18N.Locale)
    end

  end

end

if $0 == __FILE__
  SimpleI18N.Message.set_message("message-rbbr.txt")
  SimpleI18N.Message.keys.sort.each do |k|
    print k, " => ", SimpleI18N.Message[k], "\n"
  end
end
