#! /usr/bin/python

import sys, locale, os, gtk, gobject

try:
    currentLocale = locale.setlocale(locale.LC_ALL, '')
except:
    pass

sys.path.append("/usr/share/utf8-migration-tool/pylib")

import configure
from wizard.wizard import Wizard
from gdmConfigParser import gdmConfigParser

w = Wizard()
w.load_steps()

section = "Desktop"
option = "Language"

dmrclocale = ""

def findEncoding(locale):
    f = open("/usr/share/i18n/SUPPORTED")
    for line in f.readlines():
        if line.split(" ")[0] == locale:
            return line.split(" ")[1].strip()
    raise "LocaleNotFound"

def getconfig():
    config = gdmConfigParser()
    try: 
        config.readfp(open(os.path.expanduser('~/.dmrc')))
    except:
        print "Unexpected error:", sys.exc_info()[0]
        raise
    return config

dmrc = getconfig()
if not dmrc.has_section(section):
    dmrc.add_section(section)
if not dmrc.has_option(section, option):
    try:
        dmrc.set(section, option, locale.getlocale(locale.LC_ALL)[0])
    except ValueError:
        print "Locale does not exist"
        # Locale does not exist -- handle this sanely
        # FIXME
        pass

dmrclocale = dmrc.get(section, option)
# If dmrc is empty, we are most certainly in a C locale.
# if dmrclocale == "C" or dmrclocale is None:
#     dialog = gtk.MessageDialog(
#         parent         = None,
#         flags          = gtk.DIALOG_DESTROY_WITH_PARENT,
#         type           = gtk.MESSAGE_INFO,
#         buttons        = gtk.BUTTONS_OK,
#         message_format = "Your current locale is C, which does not have any UTF-8 equivalent or it is an unsupported locale.  Please pick a supported language from /usr/share/i18n/SUPPORTED and log in through gdm again")
#     dialog.set_title('No UTF8 equivalent locale')
#     dialog.connect('response', lambda dialog, response: sys.exit(1))
#     dialog.show()
#     gtk.main()

currentEncoding = ""
try:
    currentEncoding = findEncoding(dmrclocale)
except "LocaleNotFound":
    pass

w['Login'].currentLocale = dmrclocale
w['Login'].currentEncoding = currentEncoding
w['FileNameConversion'].currentEncoding = currentEncoding

if w['Login'].currentEncoding != "UTF-8":
    w['Login'].newLocale = w['Login'].currentLocale + ".UTF-8"
else:
    w['Login'].newLocale = w['Login'].currentLocale

w['Login'].newEncoding = "UTF-8"

def change_setup(self, user_data):
    w = user_data
    dmrc.set(section, option, w['Login'].getNewLocale())
    f = open(os.path.expanduser('~/.dmrc'), "w")
    dmrc.write(f)
    f.close()
    for (oldfile, newfile) in w["FileNameConversion"].get_files():

        os.rename(oldfile, newfile)

        # FIXME -- handle exceptions in case user doesn't have write
        # access to whole of home directory.

w.connect("finished", change_setup, w)

w.run(True, main=True)

