#!/usr/bin/env python

import gtk, gconf
import os, re, sys

from utils.HIGDialog import HIGDialog

class MigrationTool:

    # Displays the main window...
    def __init__(self):

        m =  "This tool will safely migrate your settings from old versions of "
        m += "gDesklets (0.26.x series), so that they will work with versions "
        m += "0.30 onwards."

        dialog = HIGDialog(gtk.STOCK_DIALOG_INFO,
                           "gDesklets Config Migration Tool", m,
                           (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                            gtk.STOCK_OK, gtk.RESPONSE_OK))
        self.__config_path = "/apps/gdesklets"
        self.__gdesklets_path = os.path.join(os.getenv("HOME"), ".gdesklets")

        dialog.connect("response", self.__response)

        # check if ~/.gdesklets exists
        if (not os.path.exists(self.__gdesklets_path)):
            print ("You don't have a working version of gDesklets!\nExiting!")
            sys.exit(1)

        dialog.show()


    def __response(self, dialog, response):

        if (response == gtk.RESPONSE_OK):
            dialog.hide()
            self.__show_warning(dialog)
        elif (response == gtk.RESPONSE_YES):
            dialog.hide()
            self.__migrate(dialog)
        else: gtk.main_quit()


    def __show_warning(self, widget):

        m  = "This will overwrite any existing 0.30 settings!\n"
        m += "Do you wish to continue?"

        dialog = HIGDialog(gtk.STOCK_DIALOG_QUESTION, "Warning!", m,
                           (gtk.STOCK_NO, gtk.RESPONSE_NO,
                            gtk.STOCK_YES, gtk.RESPONSE_YES))
        dialog.connect("response", self.__response)
        dialog.show()


    def __show_finished(self, dialog):

        dialog = HIGDialog(gtk.STOCK_DIALOG_INFO, "Migration successful!",
                           "Settings have been migrated succesfully",
                           (gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE))
        dialog.connect("response", self.__response)
        dialog.show()


    def __show_noconfig(self, dialog):

        m  = "I could find no settings to migrate in the default profile!\n\n"
        m += "You probably have never configured or run gdesklets 0.26.x and "
        m += "so don't need to run this tool at all."

        dialog = HIGDialog(gtk.STOCK_ERROR, "Nothing To Do!", m,
                           (gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE))
        dialog.connect("response", self.__response)
        dialog.show()


    def __migrate(self, dialog):

        # we assume they have a config to start with
        noconfig = False;

        # set up gconf client
        self.__client = gconf.client_get_default()
        self.__client.add_dir(self.__config_path, gconf.CLIENT_PRELOAD_RECURSIVE)

        # open the new output files
        d_cfile = open(self.__gdesklets_path + "/displays", "w")
        p_cfile = open(self.__gdesklets_path + "/positions", "w")

        # get the current default profile
        p = self.__client.get(self.__config_path + "/profile")
        if (p):
            d_cfile.write(p.get_string() +"\n")

        # for each profile in /apps/gdesklets/profiles/, write display info to
        # the "displays" file
        # also for each id encountered, write real-x and real-y to the
        # "positions" file
        profiles = self.__client.all_dirs(self.__config_path + "/profiles")

        for p in profiles:

            profile_name = p[len(self.__config_path + "/profiles/"):]

            display_list = (self.__client.get(p + "/main/displays")).get_string()
            displays = display_list.split(",")

            for d in displays:

                d_info = d.split("::")

                if (d_info[0] != ""):
                     x_pos = (self.__client.get(p + "/" + d_info[0] +
                                                "_default_/real-x")).get_string()
                     y_pos = (self.__client.get(p + "/" + d_info[0] +
                                                "_default_/real-y")).get_string()

                     # write the data that was in gconf to the new config files
                     d_cfile.write("id" + d_info[0] + " " + d_info[1] + " " +
                                   profile_name +"\n")
                     p_cfile.write("id" + d_info[0] + " " + x_pos + " " +
                                   y_pos +"\n")

                     # check if settings exist for this display -- if so, they
                     # have to be moved in gconf
                     plist = " ".join(self.__client.all_dirs(p))
                     pattern = re.compile(d_info[0]+'[A-Za-z]+')

                     for match in (pattern.findall(plist)):
                         # copy all the entries to new location
                         entries = self.__client.all_entries(p + "/" + match)
                         for entry in entries:
                             key  = entry.get_key()
                             nkey = self.__config_path + "/id" + match + "/" + \
                                    key[len(p +"/" + match) + 1:]
                             self.__client.set(nkey, entry.get_value())
                else:
                     if (profile_name == "default"): noconfig = True

        # we are done...
        if (noconfig == False):
            self.__show_finished(dialog)
        else:
            self.__show_noconfig(dialog)



if __name__ == "__main__":

     MigrationTool()
     gtk.main()
