=begin
  gettext/cgi.rb - GetText for CGI

  Copyright (C) 2005  Masao Mutoh

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

  $Id: cgi.rb,v 1.2 2005/08/27 18:52:20 mutoh Exp $
=end

require 'cgi'
require 'gettext'

module Locale
  alias :orig_get :get

  @@cgi = nil

  module_function
  def cgi=(cgi)
    @@cgi = cgi
  end

  def cgi
    @@cgi = CGI.new unless @@cgi
    @@cgi
  end

  def get
    @@cgi = CGI.new unless @@cgi
    if ret = @@cgi["lang"] and ret.size > 0
      $stderr.print "query_string: lang = #{ret}\n" if $DEBUG
    elsif ret = @@cgi.cookies["lang"][0]
      print "cookie: lang = #{ret}\n" if $DEBUG
    elsif lang = @@cgi.accept_language
      $stderr.print "accept lanaugage: lang = #{lang}\n" if $DEBUG
 
      lang = lang.split(',').first.split('-') rescue []
      language = lang[0]
      dialect  = lang[1]
      language = language ? language.downcase : 'en' # default is en
      dialect  = dialect ? "_#{dialect.upcase}" : ""
      ret = "#{language}#{dialect}"
    else
      ret = "en"
    end
    $stderr.print "Locale.get = #{ret}\n" if $DEBUG
    ret
  end

  def codeset
    @@cgi = CGI.new unless @@cgi
    codesets = @@cgi.accept_charset
    if codesets
      ary = codesets.split(',')
      ary[0]
    else
      "UTF-8"
    end
  end

  alias :charset :codeset
  alias :set_cgi :cgi=

  module_function :charset, :set_cgi
end

module GetText
  def cgi=(cgi)
    @cgi = cgi
    Locale.cgi = cgi
  end

  def cgi
    @cgi = Locale.cgi unless @cgi
    @cgi
  end

  alias :set_cgi :cgi=

  module_function :cgi=, :set_cgi, :cgi
end
