#! /usr/bin/env python
# -*- coding: utf8 -*-

"""
Copyright (C) 2007 Adolfo González Blázquez <code@infinicode.org>

This program 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 2
of the License, or (at your option) any later version. 

This program 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 this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

If you find any bugs or have any suggestions email: code@infinicode.org
"""

import pygtk
pygtk.require("2.0")
import gtk
import gobject
gobject.threads_init()

from threading import Thread

import donkeystats
import preferences
import tools

class MLDonkeyStatsIcon:

        def __init__(self):

                        self._VERSION = '0.0.1'

                        self.max = 100
                        self.debug = True

                        self.icon = gtk.StatusIcon()
                        self.image = 'images/icon0.png'
                        self.icon.set_from_file(self.image)
                        self.icon.set_visible(True)

                        self.icon.connect('activate', self.on_icon_activate)
                        self.icon.connect('popup-menu', self.on_popup_menu)

                        self.prefs = preferences.Preferences(self)
                        self.menu = self.create_menu()

                        # Init the stats module as a thread
                        self.t = Thread(target=donkeystats.DonkeyStats, args=([self, self.debug]))
                        self.t.start()

                        self.keep = True
                        self.reconnect = False


        def create_menu(self):

                menu = gtk.Menu()

                reconnect = gtk.ImageMenuItem(stock_id=gtk.STOCK_REFRESH, accel_group=None)
                reconnect.connect('activate', self.start_reconnect)

                sep1 = gtk.SeparatorMenuItem()

                pref = gtk.ImageMenuItem(stock_id=gtk.STOCK_PREFERENCES, accel_group=None)
                pref.connect("activate", self.show_preferences)

                about = gtk.ImageMenuItem(stock_id=gtk.STOCK_ABOUT, accel_group=None)
                about.connect("activate", self.about_dialog)

                sep2 = gtk.SeparatorMenuItem()

                quit = gtk.ImageMenuItem(stock_id=gtk.STOCK_QUIT, accel_group=None)
                quit.connect("activate", self.quit)

                menu.add(reconnect)
                menu.add(sep1)
                menu.add(pref)
                menu.add(about)
                menu.add(sep2)
                menu.add(quit)

                menu.show_all()
                return menu

        def quit(self, widget):
                gtk.main_quit()
                self.keep = False

        def show_preferences(self, widget):
                self.prefs.show()

        def get_keep(self):
                return self.keep

        def start_reconnect(self, widget):
                self.reconnect = True
                if not self.t.isAlive():
                        # Init the stats module as a thread
                        self.t.join()
                        self.t = None
                        self.t = Thread(target=donkeystats.DonkeyStats, args=([self, self.debug]))
                        self.t.start()
                        print self.t

        def get_reconnect(self):
                return self.reconnect

        def on_icon_activate(self, icon):
                pass

        def on_popup_menu(self, status, button, time):
                self.menu.popup(None, None, gtk.status_icon_position_menu, button, time, self.icon)

        def set_stats_text(self, stats):
                up = str(stats[0])
                down = str(stats[1])
                count = str(stats[2])
                active = str(stats[3])
                share_files = str(stats[4])
                share_size = str(stats[5])
                uploaded = stats[6]
                uploaded = tools.size_human(uploaded)

                text  = "Up  : " + up + " KB/s\n"
                text += "Down: " + down + " KB/s" # (" + active + "/" + count + ")\n"
                """
                text += "\n"
                text += "Shares: " + share_files + " ("+share_size+")\n"
                text += "Uploaded: " + uploaded
                """
                text += "\n\nHost: " + self.prefs.get_host()
                gobject.idle_add(self.icon.set_tooltip, text)

        def set_icon(self, stats):
                down = float(stats[1])
                dmax = self.max
                dval = round ((down * 100.00) / dmax)
                dval = int(round(dval/10)*10)
                if dval >= 100: dval = 100
                if dval <= 0: dval = 0

                # This generates the icon dynamically using cairo
                # and add it to the StatusIcon
                #gobject.idle_add(lambda: self.icon.set_from_pixbuf(dynamic_icon.generate_image(dval)))

                # This uses diferrent icons for each state
                gobject.idle_add(self.icon.set_from_file, 'images/icon'+str(dval)+'.png')


        def show_icon(self, state):
                gobject.idle_add(self.icon.set_visible, state)

        def set_text_error(self, text):
                        gobject.idle_add(self.icon.set_tooltip, text)

        def set_icon_error(self):
                gobject.idle_add(self.icon.set_from_file, 'images/icon_error.png')

        def about_dialog(self, event, data=None):
                """ Display the About dialog """

                about = gtk.AboutDialog()
                about.set_name('MLDonkey Stats Icon')
                about.set_version(self._VERSION)
                about.set_authors(["Adolfo González Blázquez <code@infinicode.org>"])
                about.set_logo(gtk.gdk.pixbuf_new_from_file('images/icon.png'))
                about.set_license('GPL2')
                about.set_wrap_license(True)
                about.set_comments('Status icon to control MLDonkey statistics')
                about.set_copyright('Copyright © 2007 Adolfo González Blázquez')

                def openHomePage(widget,url,url2):
                    import webbrowser
                    webbrowser.open_new(url)

                gtk.about_dialog_set_url_hook(openHomePage, 'http://www.infinicode.org/')
                about.set_website('http://www.infinicode.org/code/mldonkeystatsicon/')
                about.set_icon_from_file('images/icon.png')
                about.run()
                about.destroy()


if __name__ == "__main__":

        try:
                m = MLDonkeyStatsIcon()
                gtk.main()
        except KeyboardInterrupt:
                m.keep = False