# Maegios (Nagios client for Maemo) - Host/service status browser application.
#
# Copyright 2009-2010 Vladimir Semenov <vlad@vsemenov.com>
#
# This file is part of Maegios.
#
# Maegios is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Maegios is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Maegios.  If not, see <http://www.gnu.org/licenses/>.

import sys, os, time, threading
import gtk, hildon, hildondesktop, pango, cairo, gobject
import socket, base64
import gettext
from gnome import gconf
from nagiosconnector import NagiosConnector, NagiosParser

gettext.install('maegios')

default_config = {'url': 'http://yourdomain.com/nagios', 
                  'username': base64.b64encode('nagiosuser'),
                  'password': base64.b64encode('nagiospass'),
                  'interval': '5',
                  'attempts': '3',
                  'is_configured': '0',
                  'notify_banner': '1',
                  'notify_sound': '1',
                  'notify_vibration': '1',
                  'notify_light': '1'}
                  
class UIMaegios():
    """Maegios application for viewing host/service details and configuring settings.
    """
    def __init__(self, hostdata = None):
        global default_config
        
        self.config = default_config
        self.hostdata = hostdata
        
        # read config from gconf
        if not gconf.client_get_default().dir_exists('/apps/maegios'):
            gconf.client_get_default().add_dir('/apps/maegios', gconf.CLIENT_PRELOAD_NONE)
            # update maegios configuration:
            gconf.client_get_default().set_string('/apps/maegios/url', self.config['url'])
            gconf.client_get_default().set_string('/apps/maegios/username', self.config['username'])
            gconf.client_get_default().set_string('/apps/maegios/password', self.config['password'])
            gconf.client_get_default().set_string('/apps/maegios/interval', self.config['interval'])
            gconf.client_get_default().set_string('/apps/maegios/attempts', self.config['attempts'])
            gconf.client_get_default().set_string('/apps/maegios/is_configured', self.config['is_configured'])
            gconf.client_get_default().set_string('/apps/maegios/notify_banner', self.config['notify_banner'])
            gconf.client_get_default().set_string('/apps/maegios/notify_sound', self.config['notify_sound'])
            gconf.client_get_default().set_string('/apps/maegios/notify_vibration', self.config['notify_vibration'])
            gconf.client_get_default().set_string('/apps/maegios/notify_light', self.config['notify_light'])
            
        if gconf.client_get_default().get_string('/apps/maegios/notify_banner') == None:
            gconf.client_get_default().set_string('/apps/maegios/notify_banner', self.config['notify_banner'])    
        if gconf.client_get_default().get_string('/apps/maegios/notify_sound') == None:
            gconf.client_get_default().set_string('/apps/maegios/notify_sound', self.config['notify_sound'])
        if gconf.client_get_default().get_string('/apps/maegios/notify_vibration') == None:
            gconf.client_get_default().set_string('/apps/maegios/notify_vibration', self.config['notify_vibration'])
        if gconf.client_get_default().get_string('/apps/maegios/notify_light') == None:    
            gconf.client_get_default().set_string('/apps/maegios/notify_light', self.config['notify_light'])
            
        # load maegios configuration from gconf:
        if gconf.client_get_default().dir_exists('/apps/maegios'):
            self.config['url'] = gconf.client_get_default().get_string('/apps/maegios/url')
            self.config['username'] = gconf.client_get_default().get_string('/apps/maegios/username')
            self.config['password'] = gconf.client_get_default().get_string('/apps/maegios/password')
            self.config['interval'] = gconf.client_get_default().get_string('/apps/maegios/interval')
            self.config['attempts'] = gconf.client_get_default().get_string('/apps/maegios/attempts')
            self.config['is_configured'] = gconf.client_get_default().get_string('/apps/maegios/is_configured')                    
            self.config['notify_banner'] = gconf.client_get_default().get_string('/apps/maegios/notify_banner')           
            self.config['notify_sound'] = gconf.client_get_default().get_string('/apps/maegios/notify_sound')     
            self.config['notify_vibration'] = gconf.client_get_default().get_string('/apps/maegios/notify_vibration')     
            self.config['notify_light'] = gconf.client_get_default().get_string('/apps/maegios/notify_light')                                          
        self.filter = "new"

    def set_pix(self, filename):
        pixbuf = gtk.gdk.pixbuf_new_from_file(filename)
        return pixbuf
    
    def create_model_loading(self):
        lstore = gtk.TreeStore(gtk.gdk.Pixbuf, gobject.TYPE_STRING, gobject.TYPE_STRING)
        liter = lstore.append(None)
        lstore.set(liter, 2, "", 1, _(u"Fetching data, please wait..."), 0, None)
        return lstore
            
    def create_model(self, filter = "new", hostdata = None):
        lstore = gtk.TreeStore(gtk.gdk.Pixbuf, gobject.TYPE_STRING, gobject.TYPE_STRING)

        data = ["OK", "WARN", "CRIT"]
        hostIcons = ["/usr/share/icons/hicolor/64x64/hildon/maegios-host-ok-64x64.png", 
                     "/usr/share/icons/hicolor/64x64/hildon/maegios-host-warn-64x64.png", 
                     "/usr/share/icons/hicolor/64x64/hildon/maegios-host-crit-64x64.png"]

        serviceIcons = ["/usr/share/icons/hicolor/64x64/hildon/maegios-service-ok-64x64.png", 
                        "/usr/share/icons/hicolor/64x64/hildon/maegios-service-warn-64x64.png", 
                        "/usr/share/icons/hicolor/64x64/hildon/maegios-service-crit-64x64.png",

                        "/usr/share/icons/hicolor/64x64/hildon/maegios-disconnected-64x64.png"]
        remainingAttempts = int(gconf.client_get_default().get_string('/apps/maegios/attempts'))

        # Use data from the widget if available:
        if hostdata != None and (filter == "new" or filter == "problems"):
            hosts = hostdata
        else:
            # Attempt to retrieve data from nagios
            while remainingAttempts > 0:
                #print "connection attempts [app]: %d" % remainingAttempts
                try:
                    # Load and parse nagios data
                    if filter == "new":
                        parser = NagiosParser(only_active = 1)
                    else:
                        parser = NagiosParser()
                    connector = NagiosConnector(self)
                    if filter == "new" or filter == "problems":
                        parser.feed(connector.get_down_hosts())
                    elif filter == "all":
                        parser.feed(connector.get_all_hosts())
                    parser.close()
                    hosts = parser.get_hosts()
                    break
                except:
                    remainingAttempts -= 1
                    time.sleep(0.1)
                
        if remainingAttempts == 0:
            liter = lstore.append(None)
            lstore.set(liter, 2, "", 1, _(u"Disconnected"), 0, self.set_pix(serviceIcons[3]))        
        else:
            if len(hosts) == 0:
                liter = lstore.append(None)
                nothingFoundString = str()
                if filter == "new":
                    nothingFoundString = _(u"All good!")
                    nothingFoundInfo = _(u"(no new alerts)")
                elif filter == "all":
                    nothingFoundString = _(u"No services or hosts found in Nagios")
                    nothingFoundInfo = ""
                elif filter == "problems":
                    nothingFoundString = _(u"No problems with services or hosts found in Nagios")
                    nothingFoundInfo = ""
                lstore.set(liter, 2, nothingFoundInfo, 1, nothingFoundString, 0, \
                self.set_pix(serviceIcons[0]))
            else:
                iconlist = []
                for host in hosts:
                    criticalServices = 0
                    warningServices = 0
                    for service in host['services']:
                        if service['status'] == "CRITICAL":
                            criticalServices += 1
                        elif service['status'] == "WARNING":
                            warningServices += 1
                            
                    hostStatusString = str()
                    if warningServices > 0:
                        hostStatusString = _(u"%d WARNING") % warningServices
                        hostItemIcon = hostIcons[1] 
                    elif criticalServices > 0:
                        hostStatusString = _(u"%d CRITICAL") % criticalServices
                        hostItemIcon = hostIcons[2]
                    else:
                        if len(host['services']) > 0:
                            hostStatusString = _(u"%d OK") % len(host['services'])
                            hostItemIcon = hostIcons[0]
                        else:
                            if host['host']['status'] == 'UP':
                                hostItemIcon = hostIcons[0]  
                            else:
                                hostItemIcon = hostIcons[2]  
                            
                    iconlist.append([host['host']['hostname'], hostItemIcon, hostStatusString])

                for item in iconlist:
                    liter = lstore.append(None)
                    lstore.set(liter, 2, item[2], 1, item[0], 0, self.set_pix(item[1]))
                    for host in hosts:
                        if host['host']['hostname'] == item[0]:
                            for service in host['services']:
                                statusIcon = serviceIcons[0]
                                if service['status'] == 'WARNING':
                                    statusIcon = serviceIcons[1]
                                elif service['status'] == 'CRITICAL':
                                    statusIcon = serviceIcons[2]
                                lstore.append(liter, [self.set_pix(statusIcon), \
                                "    %s" % service['name'], service['info']])

        return lstore

    def add_columns_to_treeview(self, treeview):
        # column 0
        renderer = gtk.CellRendererPixbuf()
        column = gtk.TreeViewColumn()
        column.pack_start(renderer, True)
        column.add_attribute(renderer, "pixbuf", 0)
        treeview.append_column(column)

        # column 1
        renderer = gtk.CellRendererText()
        column = gtk.TreeViewColumn('title', renderer, text = 1)
        column.set_property("expand", False)
        column.set_sizing(gtk.TREE_VIEW_COLUMN_AUTOSIZE)
        treeview.append_column(column)

        # column 2
        renderer = gtk.CellRendererText()
        renderer.set_property('xalign', 1.0)
        column = gtk.TreeViewColumn('title', renderer, text = 2)
        column.set_property("expand", False)
        column.set_sizing(gtk.TREE_VIEW_COLUMN_AUTOSIZE)
        treeview.append_column(column)

    def create_menu(self, label):
        self.menu = hildon.AppMenu()

        # Nagios Settings
        self.button = hildon.GtkButton(gtk.HILDON_SIZE_AUTO)
        self.button.set_label(_(u"Nagios Configuration"))
        dialog = UINagiosConfigurationDialog(self)
        self.button.connect("clicked", dialog.display)
        self.menu.append(self.button)

        # Refresh Settings
        self.button = hildon.GtkButton(gtk.HILDON_SIZE_AUTO)
        self.button.set_label(_(u"Refresh Settings"))
        dialog = UIRefreshSettingsDialog(self)
        self.button.connect("clicked", dialog.display)
        self.menu.append(self.button)
       
        # Notification Settings
        self.button = hildon.GtkButton(gtk.HILDON_SIZE_AUTO)
        self.button.set_label(_(u"Notification Settings"))
        dialog = UINotificationSettingsDialog(self)
        self.button.connect("clicked", dialog.display)
        self.menu.append(self.button)       
       
        # Force Refresh
        self.button = hildon.GtkButton(gtk.HILDON_SIZE_AUTO)
        self.button.set_label(_(u"Force Refresh"))
        self.button.connect("clicked", self.force_refresh)
        self.menu.append(self.button)
        
        # About Maegios
        self.button = hildon.GtkButton(gtk.HILDON_SIZE_AUTO)
        self.button.set_label(_(u"About Maegios"))
        dialog = UIAboutDialog(self)
        self.button.connect("clicked", dialog.display)
        self.menu.append(self.button)
       
        # Create filters
        
        # All Hosts
        self.button = hildon.GtkRadioButton(gtk.HILDON_SIZE_AUTO, None)
        self.button.set_label(_(u"All Hosts"))
        self.button.connect("clicked", self.filter_all, label)
        self.menu.add_filter(self.button)
        self.button.set_mode(False)

        # Problem Hosts
        self.button = hildon.GtkRadioButton(gtk.HILDON_SIZE_AUTO, None)
        self.button.set_label(_(u"Problems"))
        self.button.connect("clicked", self.filter_problems, label)
        self.menu.add_filter(self.button)
        self.button.set_mode(False)    
        
        # New Failures
        self.button = hildon.GtkRadioButton(gtk.HILDON_SIZE_AUTO, None)
        self.button.set_label(_(u"New Alerts"))
        self.button.connect("clicked", self.filter_new, label)
        self.menu.add_filter(self.button)
        self.button.set_mode(False)      

        self.menu.show_all()

        return self.menu

    def display(self):
        self.window = hildon.StackableWindow()
        
        # Set window title
        self.window.set_title("Maegios")
        # Create menu
        self.label2 = gtk.Label(_(u"No menu option has been selected yet."))
        self.menu = self.create_menu(self.label2)
        # Attach menu to the window
        self.window.set_app_menu(self.menu)

        self.parea = hildon.PannableArea()
        self.parea.set_property("mov-mode", hildon.MOVEMENT_MODE_BOTH);
        # gtk.HILDON_UI_MODE_NORMAL -> not selection in the treeview
        # gtk.HILDON_UI_MODE_EDIT -> selection in the treeview
        self.treeview = hildon.GtkTreeView(gtk.HILDON_UI_MODE_EDIT)
        # this is pointless if we haven't been configured
        if int(gconf.client_get_default().get_string('/apps/maegios/is_configured')) == 1:
            # load data from nagios asynchronously
            self.model = self.create_model_loading()
            self.treeview.set_model(self.model)
            self.thread = threading.Thread(target = self.async_fetch)
            self.thread.start()
        
        #self.treeview.set_level_indentation(30)
        self.add_columns_to_treeview(self.treeview)
        self.treeview.columns_autosize()
        self.parea.add(self.treeview)
        #self.parea.scroll_to(0, 0)
        self.treeview.expand_all()

        if int(gconf.client_get_default().get_string('/apps/maegios/is_configured')) == 0:
            label = gtk.Label(_(u"Please configure Maegios with information about your Nagios instance."))
            button = hildon.Button(gtk.HILDON_SIZE_AUTO_WIDTH | 
                                   gtk.HILDON_SIZE_FINGER_HEIGHT,
                                   hildon.BUTTON_ARRANGEMENT_VERTICAL)
            button.set_label(_(u"Nagios Configuration"))
            dialog = UINagiosConfigurationDialog(self)             
            button.connect("clicked", dialog.display)
            self.vbox = gtk.VBox(True, 80)
            self.vbox.set_spacing(15)
            self.vbox.pack_start(label, False, False, 0)
            self.vbox.pack_start(button, False, False, 0)
            self.window.add(self.vbox)
        else:
            self.window.add(self.parea)
        
        self.window.connect("destroy", self.quit)
        
        self.window.show_all()
   
    def quit(self, widget = None, label = None):
        self.thread.join()
        gtk.main_quit()
   
    def force_refresh(self, widget = None):
        # refresh app
        self.refresh(widget)
        # refresh widget
        self.reload_widget()

    def async_fetch(self):
        self.model = self.create_model(self.filter, self.hostdata)
        self.hostdata = None
        self.treeview.set_model(self.model)    
        self.treeview.show_all()
   
    def refresh(self, widget = None):
        # load data from nagios asynchronously
        self.model = self.create_model_loading()
        self.treeview.set_model(self.model)  
        self.treeview.show_all()
        self.thread = threading.Thread(target = self.async_fetch)
        self.reload_widget()        
        self.thread.start()
        
    def filter_all(self, widget, label):
        self.filter = "all"
        self.refresh(widget)
        self.treeview.collapse_all()
        
    def filter_problems(self, widget, label):
        self.filter = "problems"
        self.refresh(widget)
        
    def filter_new(self, widget, label):
        self.filter = "new"
        self.refresh(widget)
        self.treeview.expand_all()
        
    def reload_widget(self):
        """Signals desktop widget to reload on configuration change
        """
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect(('', gconf.client_get_default().get_int('/apps/maegios/widget_port')))
            s.send('RE')
            data = s.recv(2)
            s.close()
        except:
            pass
            #traceback.print_exc()

class UINagiosConfigurationDialog():
    """Creates and displays a dialog to set Nagios server settings
    """
    def __init__(self, toplevel = None):
        self.toplevel = toplevel

    def display(self, widget):
        self.window = hildon.StackableWindow()
        self.window.set_title(_(u"Nagios Configuration"))

        self.labelUrl = gtk.Label(_(u"Nagios URL:"))
        self.labelUrl.set_width_chars(15)
        self.labelUrl.set_alignment(1.0, 0.5)
        self.labelUsername = gtk.Label(_(u"Nagios Username:"))
        self.labelUsername.set_width_chars(15)
        self.labelUsername.set_alignment(1.0, 0.5)
        self.labelPassword = gtk.Label(_(u"Nagios Password:"))
        self.labelPassword.set_width_chars(15)
        self.labelPassword.set_alignment(1.0, 0.5)

        self.entryUrl = hildon.Entry(0)
        self.entryUrl.set_text(gconf.client_get_default().get_string('/apps/maegios/url'))

        self.entryUsername = hildon.Entry(0)
        self.entryPassword = hildon.Entry(0)
        self.entryPassword.set_visibility(False)
        self.entryUsername.set_max_length(32)
        self.entryUsername.set_max_length(32)
        
        username = str()
        password = str()
        try:
            username = base64.b64decode(gconf.client_get_default().get_string('/apps/maegios/username'))
            password = base64.b64decode(gconf.client_get_default().get_string('/apps/maegios/password'))
        except:
            pass
            
        self.entryUsername.set_text(username)
        self.entryPassword.set_text(password)

        self.buttonSave = hildon.Button(gtk.HILDON_SIZE_AUTO_WIDTH | 
                                        gtk.HILDON_SIZE_FINGER_HEIGHT,
                                        hildon.BUTTON_ARRANGEMENT_VERTICAL)
        self.buttonSave.set_label(_(u"Save"))

        self.buttonUndo = hildon.Button(gtk.HILDON_SIZE_AUTO_WIDTH | 
                                        gtk.HILDON_SIZE_FINGER_HEIGHT,
                                        hildon.BUTTON_ARRANGEMENT_VERTICAL)
        self.buttonUndo.set_label(_(u"Clear"))

        self.vbox = gtk.VBox(True, 1)

        # URL
        self.hboxUrl = gtk.HBox(False, 0)
        self.hboxUrl.pack_start(self.labelUrl, False, False, 20)
        self.hboxUrl.pack_start(self.entryUrl, True, True, 20)
        self.vbox.pack_start(self.hboxUrl, False, False, 0)

        # Username
        self.hboxUsername = gtk.HBox(False, 0)
        self.hboxUsername.pack_start(self.labelUsername, False, False, 20)
        self.hboxUsername.pack_start(self.entryUsername, True, True, 20)
        self.vbox.pack_start(self.hboxUsername, False, False, 0)

        # Password
        self.hboxPassword = gtk.HBox(False, 0)
        self.hboxPassword.pack_start(self.labelPassword, False, False, 20)
        self.hboxPassword.pack_start(self.entryPassword, True, True, 20)
        self.vbox.pack_start(self.hboxPassword, False, False, 0)

        self.buttonBox = gtk.HBox(False, 0)
        self.buttonBox.pack_start(self.buttonSave, True, True, 50)
        self.buttonBox.pack_start(self.buttonUndo, True, True, 50)

        self.vbox.pack_start(self.buttonBox, True, False, 0)

        self.window.add(self.vbox)

        self.buttonSave.connect("clicked", self.save)
        self.buttonUndo.connect("clicked", self.undo)

        self.window.show_all()

    def save(self, button):
        """Saves Nagios server settings to gconf
        """
        gconf.client_get_default().set_string('/apps/maegios/url',\
        self.entryUrl.get_text())
        gconf.client_get_default().set_string('/apps/maegios/username',\
        base64.b64encode(self.entryUsername.get_text()))
        gconf.client_get_default().set_string('/apps/maegios/password',\
        base64.b64encode(self.entryPassword.get_text()))
        
        previous_is_configured_value = int(gconf.client_get_default().get_string('/apps/maegios/is_configured'))

        gconf.client_get_default().set_string('/apps/maegios/is_configured', '1')

        # notify desktop widget that configuration has been changed
        self.toplevel.reload_widget()

        # refresh treeview
        self.toplevel.refresh()
        
        # display pannable area if we haven't yet
        if previous_is_configured_value == 0:
            if len(self.toplevel.window.get_children()) > 0:
                self.toplevel.window.remove(self.toplevel.window.get_children()[0])  
            self.toplevel.window.add(self.toplevel.parea)
            self.toplevel.window.show_all()

        button.get_toplevel().get_stack().pop(1)

        # configuration note, todo: localization
        note = hildon.hildon_note_new_information(button.get_toplevel(), \
           _(u"Your Nagios configuration has been saved, and will now be used \
to pull information from your Nagios instance."))
        response = gtk.Dialog.run(note)

    def undo(self, button):
        #button.get_toplevel().get_stack().pop(1)
        self.entryUrl.set_text("")
        self.entryUsername.set_text("")
        self.entryPassword.set_text("")
        
class UIRefreshSettingsDialog():
    """Creates and displays a dialog to set refresh settings
    """
    def __init__(self, toplevel = None):
        self.toplevel = toplevel

    def display(self, widget):
        # Create the main window
        self.window = hildon.StackableWindow()
        self.window.set_title(_(u"Refresh Settings"))

        label1 = gtk.Label(_(u"Refresh Interval:"))
        label1.set_width_chars(15)
        label1.set_alignment(1.0, 0.5)
        label2 = gtk.Label(_(u"Attempts:"))
        label2.set_width_chars(15)
        label2.set_alignment(1.0, 0.5)
        label3 = gtk.Label(_(u"minutes"))
        label3.set_alignment(0.1, 0.5)

        self.entryInterval = hildon.Entry(3)
        self.entryInterval.set_max_length(5)
        self.entryInterval.set_text(gconf.client_get_default().get_string('/apps/maegios/interval'))
        self.entryAttempts = hildon.Entry(3)
        self.entryAttempts.set_max_length(5)
        self.entryAttempts.set_text(gconf.client_get_default().get_string('/apps/maegios/attempts'))

        self.buttonSave = hildon.Button(gtk.HILDON_SIZE_AUTO_WIDTH | 
                                        gtk.HILDON_SIZE_FINGER_HEIGHT,
                                        hildon.BUTTON_ARRANGEMENT_VERTICAL)
        self.buttonSave.set_label(_(u"Save"))

        self.buttonUndo = hildon.Button(gtk.HILDON_SIZE_AUTO_WIDTH | 
                                        gtk.HILDON_SIZE_FINGER_HEIGHT,
                                        hildon.BUTTON_ARRANGEMENT_VERTICAL)
        self.buttonUndo.set_label(_(u"Clear"))

        vbox = gtk.VBox(True, 1)

        # Interval
        hboxInterval = gtk.HBox(False, 0)
        hboxInterval.pack_start(label1, False, False, 20)
        hboxInterval.pack_start(self.entryInterval, False, False, 20)
        hboxInterval.pack_start(label3, False, False, 0)
        vbox.pack_start(hboxInterval, False, False, 0)

        # Attempts
        hboxAttempts = gtk.HBox(False, 0)
        hboxAttempts.pack_start(label2, False, False, 20)
        hboxAttempts.pack_start(self.entryAttempts, False, False, 20)
        vbox.pack_start(hboxAttempts, False, False, 0)

        buttonBox = gtk.HBox(False, 0)
        buttonBox.pack_start(self.buttonSave, True, True, 50)
        buttonBox.pack_start(self.buttonUndo, True, True, 50)

        vbox.pack_start(buttonBox, True, False, 0)

        self.window.add(vbox)

        self.buttonSave.connect("clicked", self.save)
        self.buttonUndo.connect("clicked", self.undo)

        # This call show the window and also add the window to the stack
        self.window.show_all()

    def save(self, button):
        """Saves refresh settings to gconf
        """
        gconf.client_get_default().set_string('/apps/maegios/interval', self.entryInterval.get_text())
        gconf.client_get_default().set_string('/apps/maegios/attempts', self.entryAttempts.get_text())

        # notify desktop widget that configuration has been changed
        self.toplevel.reload_widget()

        # refresh treeview
        self.toplevel.refresh()

        button.get_toplevel().get_stack().pop(1)

        # configuration note
        note = hildon.hildon_note_new_information(button.get_toplevel(), \
           _(u"Your refresh settings have been saved, and will now be used \
to pull information from your Nagios instance."))
        response = gtk.Dialog.run(note)

    def undo(self, button):
        #button.get_toplevel().get_stack().pop(1)
        self.entryInterval.set_text("")
        self.entryAttempts.set_text("")

class UINotificationSettingsDialog():
    """Creates and displays a dialog to set notification settings
    """
    def __init__(self, toplevel = None):
        self.toplevel = toplevel

    def display(self, widget):
        # Create the main window
        self.window = hildon.StackableWindow()
        self.window.set_title(_(u"Notification Settings"))

        self.checkBanner = gtk.CheckButton(label = _(u" Show Banner Popup "))
        self.checkSound = gtk.CheckButton(label = _(u" Play Sound "))
        self.checkVibration = gtk.CheckButton(label = _(u" Vibrate "))
        self.checkLight = gtk.CheckButton(label = _(u" Blink LED Light "))
        
        if int(gconf.client_get_default().get_string('/apps/maegios/notify_banner')) == 1:
            self.checkBanner.set_active(True)
        if int(gconf.client_get_default().get_string('/apps/maegios/notify_sound')) == 1:
            self.checkSound.set_active(True)
        if int(gconf.client_get_default().get_string('/apps/maegios/notify_vibration')) == 1:
            self.checkVibration.set_active(True)
        if int(gconf.client_get_default().get_string('/apps/maegios/notify_light')) == 1:
            self.checkLight.set_active(True)          
        
        
        '''
        self.entryInterval.set_max_length(5)
        self.entryInterval.set_text(gconf.client_get_default().get_string('/apps/maegios/interval'))
        self.entryAttempts = hildon.Entry(3)
        self.entryAttempts.set_max_length(5)
        self.entryAttempts.set_text(gconf.client_get_default().get_string('/apps/maegios/attempts'))
        '''

        self.buttonSave = hildon.Button(gtk.HILDON_SIZE_AUTO_WIDTH | 
                                        gtk.HILDON_SIZE_FINGER_HEIGHT,
                                        hildon.BUTTON_ARRANGEMENT_VERTICAL)
        self.buttonSave.set_label(_(u"Save"))

        vbox = gtk.VBox(True, 1)

        # Banner
        checkBannerHBox = gtk.HBox(False, 0)
        checkBannerHBox.pack_start(self.checkBanner, False, False, 50)
        vbox.pack_start(checkBannerHBox, False, False, 0)

        # Sound
        checkSoundHBox = gtk.HBox(False, 0)
        checkSoundHBox.pack_start(self.checkSound, False, False, 50)
        vbox.pack_start(checkSoundHBox, False, False, 0)

        # Vibration
        checkVibrationHBox = gtk.HBox(False, 0)
        checkVibrationHBox.pack_start(self.checkVibration, False, False, 50)
        vbox.pack_start(checkVibrationHBox, False, False, 0)
        
        # Light
        checkLightHBox = gtk.HBox(False, 0)
        checkLightHBox.pack_start(self.checkLight, False, False, 50)
        vbox.pack_start(checkLightHBox, False, False, 0)        

        buttonBox = gtk.HBox(False, 0)
        buttonBox.pack_start(self.buttonSave, True, True, 50)
        #buttonBox.pack_start(buttonBox, True, True, 50)

        vbox.pack_start(buttonBox, True, False, 0)

        self.window.add(vbox)

        self.buttonSave.connect("clicked", self.save)

        # This call show the window and also add the window to the stack
        self.window.show_all()

    def save(self, button):
        """Saves user notification settings to gconf
        """
        gconf.client_get_default().set_string('/apps/maegios/notify_banner', \
            str(int(self.checkBanner.get_active())))
        gconf.client_get_default().set_string('/apps/maegios/notify_sound', \
            str(int(self.checkSound.get_active())))
        gconf.client_get_default().set_string('/apps/maegios/notify_vibration', \
            str(int(self.checkVibration.get_active())))
        gconf.client_get_default().set_string('/apps/maegios/notify_light', \
            str(int(self.checkLight.get_active())))

        # notify desktop widget that configuration has been changed
        self.toplevel.reload_widget()

        # refresh treeview
        self.toplevel.refresh()

        button.get_toplevel().get_stack().pop(1)

        # configuration note
        note = hildon.hildon_note_new_information(button.get_toplevel(), \
           _(u"Your notification settings have been changed."))
        response = gtk.Dialog.run(note)

class UIAboutDialog():
    """Creates and displays a dialog with information about this program
    """
    def __init__(self, toplevel = None):
        self.toplevel = toplevel

    def display(self, widget):
        self.window = hildon.StackableWindow()
        self.window.set_title(_(u"About Maegios"))

        labelVersion = gtk.Label("Maegios 0.4.2")
        labelNagios = gtk.Label(_(u"Tested to work with Nagios versions 2.8, 3.0.6"))
        labelLicense = gtk.Label(_(u"License: GNU General Public License verison 3"))        
        labelCredits = gtk.Label(_(u"Credits: Vladimir Semenov <vlad@vsemenov.com>"))
        vbox = gtk.VBox(True, 1)
        vbox.pack_start(labelVersion, False, False, 20)
        vbox.pack_start(labelNagios, False, False, 20)
        vbox.pack_start(labelLicense, False, False, 20)
        vbox.pack_start(labelCredits, False, False, 20)
        
        self.window.add(vbox)
        self.window.show_all()

def start(hostdata = None):
    dialog = UIMaegios(hostdata)
    dialog.display()  
    gtk.main()

