# -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4

# U8MG - an utf8 migration tool
#
# Copyright (C) 2005 Tollef Fog Heen
#
# Wizards taken from flumotion,
# Copyright (C) 2004,2005 Fluendo, S.L. (www.fluendo.com). All rights reserved.

# This file may be distributed and/or modified under the terms of
# the GNU General Public License version 2 as published by
# the Free Software Foundation.
# This file is distributed without any warranty; without even the implied
# warranty of merchantability or fitness for a particular purpose.
# See "LICENSE.GPL" in the source distribution for more information.

import gtk, os, gobject
        
import wizard

def findMatchingLocales(search, encoding = None):
    f = open("/usr/share/i18n/SUPPORTED")
    ret = []
    for line in f.readlines():
        (l, e) = line.strip().split(" ")
        if search in l and (e == encoding or encoding is None):
            ret.append(line.split(" ")[0].strip())
    return ret


class Welcome(wizard.WizardStep):
    step_name = 'Welcome'
    glade_file = 'wizard_welcome.glade'
    section = 'Welcome'
    section_name = 'Welcome'
    icon = 'wizard.png'
    has_worker = False
    def get_next(self):
        return 'Login' 
wizard.register_step(Welcome)


class Login(wizard.WizardStep):
    step_name = 'Login'
    glade_file = 'wizard_login.glade'
    section = 'Login'
    section_name = 'Login'
    icon = 'wizard.png'
    has_worker = False
    currentLocale = ""
    currentEncoding = ""
    newLocale = ""
    newEncoding = ""

    def getNewLocale(self):
        if self.currentLocale == 'C':
            return self.cbNewLocale.get_model()[self.cbNewLocale.get_active()][0]
        else:
            return self.lblNewLocale.get_text()

    def get_next(self):
        return "FileNameConversion"

    def before_show(self):
        if self.currentEncoding == 'UTF-8':
            self.lblLocaleInfo.set_label("Your login configuration is already UTF-8 enabled")
            self.tblLocaleInfo.hide()
        self.lblCurrentLocale.set_label(self.currentLocale)
        self.lblCurrentEncoding.set_label(self.currentEncoding)
        self.lblNewLocale.set_label(self.newLocale)
        self.lblNewEncoding.set_label(self.newEncoding)
        if self.currentLocale == 'C':
            self.lblNewLocale.hide()
            self.cbNewLocale.set_model(gtk.ListStore(gobject.TYPE_STRING))
            for t in findMatchingLocales("en_", encoding = "UTF-8"):
                print t
                self.cbNewLocale.get_model().append(row=[t])

            cell = gtk.CellRendererText()
            self.cbNewLocale.pack_start(cell, True)
            self.cbNewLocale.add_attribute(cell, 'text', 0)
            self.cbNewLocale.set_active(0)
            self.cbNewLocale.show()
        else:
            self.lblNewLocale.show()
            self.cbNewLocale.hide()
            
wizard.register_step(Login)


class FileNameConversion(wizard.WizardStep):
    step_name = 'FileNameConversion'
    glade_file = 'wizard_convertfiles.glade'
    section = 'Convert file names'
    section_name = 'Convert file names'
    icon = 'wizard.png'
    last_step = True
    has_worker = False
    model = gtk.ListStore(str, str, str)
    column = gtk.TreeViewColumn("File name")
    currentEncoding = ""

    def __init__(self, *params):
        super(FileNameConversion, self).__init__(params)
        self.renderer = gtk.CellRendererText()
        self.column.pack_start(self.renderer, True)
        self.column.set_attributes(self.renderer, text=2)
        self.renderer.set_property('editable', True)

    def edited_cb(self, cell, path, new_text, user_data):
        self.model[path][1] = new_text
        return

    def before_show(self):

        filenames = []
        for root, dirs, files in os.walk(os.path.expanduser('~'), topdown=False):
            for f in files+dirs:
                try:
                    unicode(f, "utf-8")
                except UnicodeDecodeError:
                    try:
                        filenames.append((root+"/"+f,
                                          root+"/"+unicode(f, self.currentEncoding).encode('utf-8'),
                                          unicode(root+"/"+f, self.currentEncoding)))
                    except UnicodeDecodeError:
                        # Sane fallback
                        filenames.append((root+"/"+f,
                                          root+"/"+unicode(f, "iso8859-1").encode('utf-8'),
                                          unicode(root+"/"+f, "iso8859-1")))

        self.set_files(filenames)

        if len(filenames) == 0:
            self.lblConvertFilesMessage.set_text("All your files have UTF-8 compatible names.  No renames needed.")
            self.scrolledwindow1.hide()
        else:
            self.tvFileNames.set_model(self.model)
            self.tvFileNames.append_column(self.column)
            self.tvFileNames.show_all()

            self.scrolledwindow1.set_resize_mode(gtk.RESIZE_IMMEDIATE)
            self.scrolledwindow1.resize_children()
            self.renderer.connect("edited", self.edited_cb, self.model)
                
    def set_files(self, files):
        for f in files:
            self.model.append(f)

    def get_files(self):
        files = []
        treeiter = self.model.get_iter_first()
        while treeiter is not None:
            files.append(self.model.get(treeiter, 0, 1))
            treeiter = self.model.iter_next(treeiter)
        return files

    def get_next(self):
        return None

wizard.register_step(FileNameConversion)


