#!/usr/bin/env python
import sys
import subprocess
import os.path
import re
import urllib

import pygtk
pygtk.require('2.0')
import gtk
import gtk.glade
import gnome
import gnomeapplet
import gnome.ui
import gobject

#import debug

try:
    import wbconfig as wbconfig
    from webboard import WebBoard
    from wbhistory import WebBoardHistory
    from wbconfig import WebBoardConfig
except:
    import webboard.wbconfig as wbconfig
    from webboard.webboard import WebBoard
    from webboard.wbhistory import WebBoardHistory
    from webboard.wbconfig import WebBoardConfig

import gettext
from gettext import gettext as _
gettext.bindtextdomain('webboard')
gettext.textdomain('webboard')
gtk.glade.bindtextdomain('webboard')
gtk.glade.textdomain('webboard')

class WebBoardApplet(gnomeapplet.Applet):

    def __init__(self, applet, iid):

        self.__gobject_init__()

        icons = gtk.icon_theme_get_default()
        self.logo_pixbuf = icons.load_icon("gtk-paste", 32, 0)
        gtk.window_set_default_icon_list(self.logo_pixbuf)

        # initialize gnome application and set up all the gnome internals
        gnome.init(wbconfig.name, wbconfig.version)    
        self.applet = applet

        self.big_evbox = gtk.EventBox()
        self.big_evbox.connect("button-press-event",self.button_press)
        self.orientation = self.applet.get_orient()
        self.applet.add(self.big_evbox)  



        self.image = gtk.Image()
        self.big_evbox.add(self.image)
        self.image.set_from_stock(gtk.STOCK_PASTE, gtk.ICON_SIZE_SMALL_TOOLBAR)

        # setup drag'n'drop
        self.big_evbox.drag_dest_set(gtk.DEST_DEFAULT_ALL, \
                                    [('text/uri-list',0 , 0)], \
                                    gtk.gdk.ACTION_COPY)
        self.big_evbox.connect("drag_data_received", \
                             self.on_applet_drag_data_received)


        self.config = WebBoardConfig()
        self.history = WebBoardHistory(self.config, self.notify)

        self.clipboard = gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD)

        self.tooltips =gtk.Tooltips()
        self.tooltips.set_tip(self.big_evbox, _("WebBoard\n"\
                                                "Publish source code "\
                                                "on a pastebin server"))

        self.applet.show_all()

    def on_applet_drag_data_received(self, widget, context, x, y, \
                                     selection, target_type, timestamp):
        """ call when we got a drop event """
        uri = selection.data.strip()
        uri_splitted = uri.split()
        for uri in uri_splitted:
            # FIXME: For multiple files the webboards are not 
            # opend simultaneously
            path = self._get_file_path_from_dnd_dropped_uri(uri)
            wb = WebBoard(self.config, self.history, file=path)
            self.config.remove_notifier(wb.on_config_changed)
            del wb

    def _get_file_path_from_dnd_dropped_uri(self, uri):
        """ helper to get a useful path from a drop uri"""
        path = urllib.url2pathname(uri) # escape special chars
        path = path.strip('\r\n\x00') # remove \r\n and NULL
        # get the path to file
        if path.startswith('file:\\\\\\'): # windows
            path = path[8:] # 8 is len('file:///')
        elif path.startswith('file://'): # nautilus, rox
            path = path[7:] # 7 is len('file://')
        elif path.startswith('file:'): # xffm
            path = path[5:] # 5 is len('file:')
        return path

    def create_webboard(self, path, clip):
        wb = WebBoard(self.config, self.history, file=path)
        self.config.remove_notifier(wb.on_config_changed)
        #debug.dumpObjects()
        del wb
    
    def notify(self, *args):
        self.history.update

    def button_press(self, widget, event):
        if event.type == gtk.gdk.BUTTON_PRESS and event.button == 3:
            self.create_menu()
        elif event.type == gtk.gdk.BUTTON_PRESS and event.button == 1:
            wb = WebBoard(self.config, self.history, clip=True)
            self.config.remove_notifier(wb.on_config_changed)
            del wb
            #debug.dumpObjects()

    def create_menu(self):
        menuxml="<popup name=\"button3\">\n"\
            "<menuitem name=\"Item 1\" verb=\"Board\" label=\"%s\" "\
            "pixtype=\"stock\" pixname=\"gtk-new\"/>\n" % _("_New WebBoard")
        verbs = [("Board", self.new_webboard)]

        # include history menu
        if len(self.history.sites) > 0:
            menuxml += "<separator/>\n"
            for id, stamp, title, url in self.history.sites:
            #for id, stamp, title, url in self.history.sites:
                age = self.history.age(id)
                menuxml += "<menuitem name=\"%s\" verb=\"%s\" label="\
                           "\"%s (%s)\"/>\n" % (id, id, title, age)
                verbs.append(("%s" % id, self.link))
            menuxml += "<separator/>\n"

        menuxml += "<menuitem name=\"Item 2\" verb=\"Prefs\" label=\"%s\" "\
                   "pixtype=\"stock\" pixname=\"gnome-stock-preferences\"/>\n" \
                   "<menuitem name=\"Item 3\" verb=\"About\" label=\"%s\" "\
                   "pixtype=\"stock\" pixname=\"gnome-stock-about\"/>\n" \
                   "</popup>" % (_("_Preferences"), _("_About"))

        verbs.extend((("Prefs", self.config.preferences),\
                     ("About", self.about_info)))
        
        #print menuxml
        self.applet.setup_menu(menuxml, verbs, None)

    def new_webboard(self, event, data=None):
        wb = WebBoard(self.config, self.history)
        self.config.remove_notifier(wb.on_config_changed)
        del wb

    def about_info(self, event, data):
        wbconfig.about_info(self)

    def link(self, event, id):
        # Copy the url to the clipboard
        url = self.history.sites[int(id)][3]
        self.clipboard.set_text(url, len=-1)
        # Open the url in a browser
        if os.path.exists('/usr/bin/gnome-open'):
            command = ['gnome-open', url]
        else:
            command = ['x-www-browser', url]
        p = subprocess.Popen(command, close_fds=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)


gobject.type_register(WebBoardApplet)

def webboard_applet_factory(applet, iid):
    WebBoardApplet(applet, iid)
    return gtk.TRUE

# run it in a gtk window
if len(sys.argv) > 1 and sys.argv[1] == "run-in-window":
    main_window = gtk.Window(gtk.WINDOW_TOPLEVEL)
    main_window.set_title("WebBoard")
    main_window.connect("destroy", gtk.main_quit) 
    app = gnomeapplet.Applet()
    webboard_applet_factory(app, None)
    app.reparent(main_window)
    main_window.show_all()
    gtk.main()
    sys.exit()

if __name__ == '__main__':
    gnomeapplet.bonobo_factory("OAFIID:GNOME_WebBoardApplet_Factory",
                                WebBoardApplet.__gtype__, 
                                "hello", "0", webboard_applet_factory)
