#!/usr/bin/env python

# Wed Sep 22 12:11:11 2010  <yves.frederix@cs.kuleuven.be>

import os
import gtk
import gobject
from threading import Thread
import mutex
import time
import ConfigParser

try:
    import pynotify
except:
    pynotify = None

gobject.threads_init()

status_colors = {\
                 True: gtk.gdk.Color(green=200./256),\
                 False: gtk.gdk.Color(red=200./256, green=0., blue=0.)}

home = os.getenv('USERPROFILE') or os.getenv('HOME')

configfile = os.path.join(home, '.bigbrotherrc')

# Some config
trayicon_file = '/usr/share/bigbrother/icons/eye.png'

blink_timeout = 30000 # milliseconds

##################################################

def notify(text):
    if pynotify is None:
        return
    n = pynotify.Notification(text)
    n.show()

class Target(Thread):
    def __init__(self, name, host, status_change_fun=None, timeout=60):
        Thread.__init__(self)
        self.name = name
        self.host = host
        self.timeout = timeout
        self.online = False

        self.status_change_fun = status_change_fun

        self.daemon = True # to make the threads quit after closing the
                           # application.

        self.ping_cmd = 'arping -f -c2 %s 2>/dev/null' % self.host

        self.mutex = mutex.mutex()

        self.status_change = False

    def update_status(self, dummy):
        print '%s \t: checking status...' % self.name
        errcode = os.system(self.ping_cmd)
        if errcode != 0 and self.online:
            self.online = False
            if self.status_change_fun is not None:
                self.status_change_fun(self)
            print '%s \t: %s went off line' % (self.name, self.host)
        elif errcode == 0 and not self.online:
            self.online = True
            if self.status_change_fun is not None:
                self.status_change_fun(self)
            print '%s \t: %s came online' % (self.name, self.host)
        else:
            print '%s \t: no change' % self.name

    def save_update_status(self):
        self.mutex.lock(self.update_status, None)
        self.mutex.unlock()

    def run(self):
        # Find initial state
        errcode = os.system(self.ping_cmd)
        self.online = (errcode == 0)

        while True:
            time.sleep(self.timeout)
            self.save_update_status()

    def get_status_text(self):
        if self.online:
            return '%s (%s) is now online' % (self.name, self.host)
        else:
            return '%s (%s) is now offline' % (self.name, self.host)

class StatusTrackerIcon:
    def __init__(self):
        self.trayicon = gtk.StatusIcon()
        self.trayicon.set_from_file(trayicon_file)
        self.trayicon.connect('popup-menu', self.on_popup_menu)
        self.trayicon.connect('activate', self.on_activate)
        self.trayicon.set_visible(True)
        self.children = []

        # Get info from config file
        for name, host in self.read_configfile():
            self.children.append(Target(name, host, self.on_status_change))

        # Start threads
        for c in self.children:
            c.start()

        # Right-click menu to be able to close the program
        menu = gtk.Menu()
        quit = gtk.ImageMenuItem(gtk.STOCK_QUIT)
        quit.connect("activate", self.destroy)
        menu.add(quit)
        menu.show_all()
        self.menu = menu

        # Internal var
        self.destroy_timer = -1
        self.blink_timer = -1

        self.window = None

    def read_configfile(self):
        c = ConfigParser.ConfigParser()
        c.read(configfile)
        assert os.path.exists(configfile), \
                'Config file "%s" does not exist... ' % configfile + \
                'You can find a sample in /usr/share/bigbrother/bigbrotherrc.sample.'
        assert c.has_section('hosts'), \
                'Configfile appears to be corrupt. We expect a [hosts] section...'

        # 1. name/host pairs
        result = []
        for i in c.options('hosts'):
            result.append([i, c.get('hosts', i)])
        result.sort() # Sort alphabetically (order from the config file is
                      # not maintained anyway...

        # 2. config
        if c.has_option('config', 'icon'):
            global trayicon_file
            trayicon_file = c.get('config', 'icon')
        if c.has_option('config', 'blink_timeout'):
            global blink_timeout
            blink_timeout = int(c.get('config', 'blink_timeout'))

        return result

    def destroy(self, widget):
        gtk.main_quit()

    def stop_blinking(self):
        print 'Timer event: stop blinking'
        self.trayicon.set_blinking(False)
        self.blink_timer = -1

    def on_status_change(self, target):
        # Execute this function if a status change event occurs
        # 1. Make trayicon start blinking
        self.trayicon.set_blinking(True)
        # 2. Stop a previously started time that stops the blinking after a
        #    timeout
        if self.blink_timer != -1:
            gobject.source_remove(self.blink_timer)
        # 3. Start a timer that stops the blinking after a timeout 
        self.blink_timer = gobject.timeout_add(blink_timeout, self.stop_blinking)
        # 4. Update the target host status 
        notify(target.get_status_text())
        target.status_change = True

    def on_popup_menu(self, status, button, time):
        # Show menu on right click on the tray icon
        self.menu.popup(None, None, None, button, time)

    def on_activate(self, widget, data=None):
        # Do stuff when left clicking on the tray icon
        
        # 1. Stop blinking
        if self.trayicon.get_blinking():
            self.trayicon.set_blinking(False)

        if self.window is not None:
            self.destroy_window(self.window, None)
            return

        # 2. Show the hosts
        window = gtk.Window(type=gtk.WINDOW_POPUP);
        self.window = window
        vbox = gtk.VBox()
        vbox.set_border_width(1)

        # Put input
        for c in self.children:
            labeltext = ' %-10s %s ' % (c.name + \
                    c.status_change * '*', '(' + c.host + ')')
#            label = gtk.Label(labeltext)
            label = gtk.Label()
            label.set_markup('<tt>%s</tt>' % labeltext)

            label.set_alignment(xalign=0, yalign=0.5)

            eb = gtk.EventBox()
            eb.modify_bg(gtk.STATE_NORMAL, status_colors[c.online])
            eb.add(label)

            vbox.pack_start(eb, True, padding=1)

            # After the popup window has been shown, unset status_change of
            # the monitored host:
            if c.status_change:
                c.status_change = False

        # Put widgets in the window
        eb = gtk.EventBox()
        eb.add(vbox)
        window.add(eb)

        # Add mouse move listener
        window.connect('leave-notify-event', self.on_mouse_away)
        window.connect('enter-notify-event', self.on_mouse_enter)
        window.connect('button-press-event', self.destroy_window)

        # Show window
        window.show_all(); 

        # Move the window
        a,rect,c = self.trayicon.get_geometry();
        offset = 0
        if rect.y < 50:
            # Tray is locate at the top
            window.move(rect.x,abs(rect.y-(self.trayicon.get_size()+offset)))
        else:
            # Tray is locate at the bottom
            window.move(rect.x,rect.y-window.get_size()[1]-offset)

    def destroy_window(self, widget, event):
        assert widget == self.window
        widget.destroy()
        self.window = None

    def try_destroy(self, widget):
        if self.window is not None:
            self.destroy_window(self.window, None)
        return False # Stop timer

    def on_mouse_enter(self, widget, event):
        if self.destroy_timer != -1:
            gobject.source_remove(self.destroy_timer)
            self.destroy_timer = -1

    def on_mouse_away(self, widget, event):
        assert widget == self.window
        self.destroy_timer = gobject.timeout_add(5000, self.try_destroy,\
                widget)

if __name__ == '__main__':
    s = StatusTrackerIcon()
    gtk.main()

# vim: expandtab tw=75
