# Copyright (C) 2006 by Intevation GmbH
# Author(s):
# Bernhard Reiter <bernhard@intevation.de>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with the software for details.

"""Support code for setting locales."""

__version__ = "$Revision: $"
# $Id: xmlsupport.py 1683 2003-08-28 15:20:57Z bh $

import locale
from locale import LC_NUMERIC, setlocale, localeconv

_verbose = 0

def setdecimalcommalocale():
    """Find and set LC_NUMERIC locale that uses comma as decimal_point.

    Return the previous locale to be able to set the previous LC_NUMERIC.
    This can be "(None, None)" or None if none was found.
    """

    # German_Germany.1252 discovered by Bernhard Reiter 200703 Windows XP
    encodings = [".UTF-8", "@euro", ".1252"]
    locales = ["de_DE", "fr_FR", "fr_BE", "German_Germany"]

    # using setlocale, because output of getlocale might not work 
    # with setlocale, which is a python problem up to at least 2.5
    oldlocale = setlocale(LC_NUMERIC)

    tries = []
    for l in locales:
        for e in encodings:
            tries.append(l + e)

    for t in tries:
        try:
            if _verbose > 0:
                print "trying", repr(t)
            setlocale(LC_NUMERIC, t)
        except locale.Error:
            continue
        break

    # did we find one?
    if localeconv()['decimal_point'] == ",":
        return oldlocale

    setlocale(LC_NUMERIC, oldlocale)
    return None

if __name__ == "__main__":
    # test and print result
    print "Searching for LC_NUMERIC locale with comma as decimal_point ..."
    _verbose = 1
    oldlocale = setdecimalcommalocale()
    if oldlocale == None:
        print "none found."
    else:
        print "found: ",
        print setlocale(LC_NUMERIC)
        setlocale(LC_NUMERIC, oldlocale)
