=begin
  gettext.rb - GetText module

  Copyright (C) 2001-2004  Masao Mutoh
  Copyright (C) 2001-2003  Masahiro Sakai

      Masahiro Sakai    <s01397ms@sfc.keio.ac.jp>
      Masao Mutoh       <mutoh@highway.ne.jp>

  You may redistribute it and/or modify it under the same
  license terms as Ruby.

  $Id: gettext.rb,v 1.13 2004/11/04 17:06:45 mutoh Exp $
=end

require 'rbconfig'
require 'gettext/mo'
require 'gettext/locale'
require 'gettext/textdomain'

module GetText
  VERSION = "0.8.0"

  @@__textdomain = Hash.new
  @@__textdomain_key = Hash.new

  def bindtextdomain(domainname, path = nil, locale = nil, charset = nil)
    locale ||= Locale.get
    charset ||= ENV["OUTPUT_CHARSET"] ? ENV["OUTPUT_CHARSET"] : Locale.codeset
    src = callersrc
    textdomain = @@__textdomain[src]
    if textdomain
      @@__textdomain_key[domainname] = textdomain
    else
      textdomain = @@__textdomain_key[domainname]
      @@__textdomain[src] = textdomain
    end
    if ! textdomain or ! textdomain.same_property?(domainname, path, locale, charset)
      textdomain = TextDomain.new(domainname, path, locale, charset)
      @@__textdomain_key[domainname] = textdomain
      @@__textdomain[src] = textdomain
    end
    @@__textdomain[src]
  end
  
  def gettext(msgid)
    textdomain = @@__textdomain[callersrc]
    textdomain ? textdomain.gettext(msgid) : msgid
  end
  
  def ngettext(msgid, msgid_plural, n)
    textdomain = @@__textdomain[callersrc]
    textdomain ? textdomain.ngettext(msgid, msgid_plural, n) : msgid
  end
  
  def N_(msgid)
    msgid
  end

  def sgettext(msgid, div = '|')
    textdomain = @@__textdomain[callersrc]
    if textdomain
      textdomain.sgettext(msgid, div)
    else
      if index = msgid.rindex(div)
        msgid = msgid[(index + 1)..-1]
      else
        msgid
      end
    end
  end

  def callersrc
    caller(2)[0].sub(/:\d+(?::in \`\S+\')?\Z/, '')
  end

  def locale=(locale)
    textdomain = @@__textdomain[callersrc]
    textdomain.set_locale(locale) if textdomain
    locale
  end

  def charset=(cs)
    textdomain = @@__textdomain[callersrc]
    textdomain.set_charset(cs) if textdomain
  end
  
  alias :setlocale :locale=
  alias :_ :gettext
  alias :n_ :ngettext
  alias :s_ :sgettext

  module_function :bindtextdomain, :N_, :gettext, :_, :ngettext, :n_, 
    :sgettext, :s_, :setlocale, :locale=, :charset=, :callersrc
end
