#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author:  Bryce Harrington <bryce@ubuntu.com>

# Copyright (C) 2010 Canonical, Ltd.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import sys
import os
import gtk

import gettext
from gettext import gettext as _
gettext.textdomain('xdiagnose')

# optional Launchpad integration
try:
    import LaunchpadIntegration
    launchpad_available = True
except:
    launchpad_available = False

# Add project root directory (enable symlink, and trunk execution).
PROJECT_ROOT_DIRECTORY = os.path.abspath(
    os.path.dirname(os.path.dirname(os.path.realpath(sys.argv[0]))))

if (os.path.exists(os.path.join(PROJECT_ROOT_DIRECTORY, 'XDiagnose'))
    and PROJECT_ROOT_DIRECTORY not in sys.path):
    sys.path.insert(0, PROJECT_ROOT_DIRECTORY)
    os.putenv('PYTHONPATH', PROJECT_ROOT_DIRECTORY) # for subprocesses

from XDiagnose import (
    AboutXDiagnoseDialog)
from XDiagnose.helpers import get_builder

class XDiagnoseWindow(gtk.Window):
    __gtype_name__ = "XDiagnoseWindow"
    
    # To construct a new instance of this method, the following notable 
    # methods are called in this order:
    # __new__(cls)
    # __init__(self)
    # finish_initializing(self, builder)
    # __init__(self)
    #
    # For this reason, it's recommended you leave __init__ empty and put
    # your inialization code in finish_intializing
    
    def __new__(cls):
        """Special static method that's automatically called by Python when 
        constructing a new instance of this class.
        
        Returns a fully instantiated XDiagnoseWindow object.
        """
        builder = get_builder('XDiagnoseWindow')
        new_object = builder.get_object("xdiagnose_window")
        new_object.finish_initializing(builder)
        return new_object

    def finish_initializing(self, builder):
        """Called while initializing this instance in __new__

        finish_initalizing should be called after parsing the UI definition
        and creating a XDiagnoseWindow object with it in order to finish
        initializing the start of the new XDiagnoseWindow instance.
        
        Put your initilization code in here and leave __init__ undefined.
        """
        # Get a reference to the builder and set up the signals.
        self.builder = builder
        self.builder.connect_signals(self)

        global launchpad_available
        if launchpad_available:
            # see https://wiki.ubuntu.com/UbuntuDevelopment/Internationalisation/Coding for more information
            # about LaunchpadIntegration
            helpmenu = self.builder.get_object('helpMenu')
            if helpmenu:
                LaunchpadIntegration.set_sourcepackagename('xdiagnose')
                LaunchpadIntegration.add_items(helpmenu, 0, False, True)
            else:
                launchpad_available = False

        # Code for other initialization actions should be added here.

    def about(self, widget, data=None):
        """Display the about box for xdiagnose."""
        about = AboutXDiagnoseDialog.AboutXDiagnoseDialog()
        response = about.run()
        about.destroy()

    def quit(self, widget, data=None):
        """Signal handler for closing the XDiagnoseWindow."""
        self.destroy()

    def on_destroy(self, widget, data=None):
        """Called when the XDiagnoseWindow is closed."""
        # Clean up code for saving application state should be added here.
        gtk.main_quit()

if __name__ == "__main__":
    # Support for command line options.
    import logging
    import optparse
    parser = optparse.OptionParser(version="%prog %ver")
    parser.add_option(
        "-v", "--verbose", action="store_true", dest="verbose",
        help=_("Show debug messages"))
    (options, args) = parser.parse_args()

    # Set the logging level to show debug messages.
    if options.verbose:
        logging.basicConfig(level=logging.DEBUG)
        logging.debug('logging enabled')

    # Run the application.
    window = XDiagnoseWindow()
    window.show()
    gtk.main()
