#!/usr/bin/python
#
# Copyright 2010 David Steele <daves@users.sourceforge.net>
# This file is part of gnome-gmail
# Available under the terms of the GNU General Public License version 2 or later
#
""" This script attempts to edit the open officeconfiguration XML file for
the current user so that the Gnome Preferred Email Application is used for the
"Send Document as Email" command.

Since OO suports only a few, specific mailers, keyed off of the mailer name, a 
compatibility script masquerades as a supported app.
"""

import os
import xml.etree.ElementTree as ET
import shutil
import gconf


class OOMailerCfg( object ):
    """ Class to support query and edit of the Open Office email handler """
    def __init__( self ):
        # OO XML paramters
        self.registry_uri = "http://openoffice.org/2001/registry"
        self.registry_ns = "oor"
        self.registry_prefix = "{" + self.registry_uri + "}"

        # OO XML path
        self.homedir = os.path.expanduser( '~' )
        self.oo_xml_path = "/.openoffice.org/3/user/registry/data/org/openoffice/Office/Common.xcu"
        self.backup_ext = ".bak"

        self.ooxmlfile = self.homedir + self.oo_xml_path

        registry_namespace = None

        # bug(?) in ElementTree
        try:
            register_namespace = ET.register_namespace
        except AttributeError:
            def register_namespace(prefix, uri):
                ET._namespace_map[uri] = prefix

        register_namespace( self.registry_ns, self.registry_uri )
        
        self.tree = ET.parse( self.ooxmlfile )
        self.root = self.tree.getroot()

    def _del_external_mailer ( self, root_node ):
        """ Delete the XML key for the existing OO mailer """
        for node in root_node:
            if( node.attrib[self.registry_prefix + 'name'] == \
                "ExternalMailer" ):
                root_node.remove( node )

    def _add_external_mailer( self, root_node, cmd ):
        """ add the key for the compatibility mailer """
        external_mailer = ET.SubElement( root_node, "node" )
        external_mailer.attrib[ self.registry_prefix + 'name'] = \
            "ExternalMailer"

        external_mailer_prop = ET.SubElement( external_mailer, "prop" )
        external_mailer_prop.attrib[ self.registry_prefix + 'name'] = \
            "Program"
        external_mailer_prop.attrib[ self.registry_prefix + 'type'] = \
            "xs:string"

        external_mailer_value = ET.SubElement( external_mailer_prop, "value" )
        external_mailer_value.text = cmd

    def get_external_mailer( self ):
        """ what is the external mailer, if any, currently configured in
        Open Office? """

        return_value = ""

        try:
            for node in self.root:
                if( node.attrib[self.registry_prefix + 'name'] == \
                        "ExternalMailer" ):
                    prop_node = node.find( "prop" )
                    value_node = prop_node.find( "value" )
                    return_value = value_node.text
        except:
            pass

        return( return_value )

    def _set_external_mailer_xml( self, cmd_path ):
        """ given a path to the OO XML file, set the external mailer """

        self._del_external_mailer( self.root )

        self._add_external_mailer( self.root, cmd_path )

        return self.tree

    def set_external_mailer( self, cmd_path ):
        """ cleanly set the external mailer, with a backup """
        if( self.get_external_mailer() != cmd_path ):
            tree = self._set_external_mailer_xml( cmd_path )

            try:
                os.unlink( self.ooxmlfile + self.backup_ext )
            except:
                pass

            shutil.move( self.ooxmlfile, self.ooxmlfile + self.backup_ext )

            tree.write( self.ooxmlfile )

def should_set_oo_mailer( basedir = "/apps/gnome-gmail/" ):
    """ is the current OO mail handler different than what we want? """

    client = gconf.client_get_default()

    the_bool = client.get_bool( basedir + "OOfix" )

    return( the_bool )


if __name__ == "__main__":

    # this is best effort
    try:
        if( should_set_oo_mailer() ):
            Oom = OOMailerCfg()

            Oom.set_external_mailer( "/usr/share/gnome-gmail/evolution" )        
    except:
        pass

