#
# Copyright 2006 Alex Lancaster
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation

import os, string, webbrowser
import gtk, gobject
import urllib
from xml.dom import minidom
import threading
from gettext import gettext as _
import rb
import rhythmdb

site_list = \
          {'google': ('Google music', "http://www.google.com/musicsearch?q=%s&res=artist", "http://www.google.com/musicsearch?q=%s&res=album", '+', 0),
           'lastfm': ('Last.fm', "http://www.lastfm.com/music/%s", "http://www.lastfm.com/music/%s/%s", '+', 1),
           'wikipedia': ('Wikipedia', "http://en.wikipedia.org/wiki/%s","http://en.wikipedia.org/wiki/%s", '_', 0),
           'allmusic': ('All Music Guide', "http://www.allmusic.com/cg/amg.dll?p=amg&opt1=1&sql=%s","http://www.allmusic.com/cg/amg.dll?p=amg&opt1=2&sql=%s", '+', 0),
           'discogs': ('Discogs', "http://www.discogs.com/artist/%s", "http://www.discogs.com/search?type=releases&q=%s", '+', 0)}

## Note: lastfm uses both artist and album for URL
## Note: allmusic uses opt1=1 for artist, opt1=2 for album

# callback method
def callback(widget, data=None):
    print "%s was linked to" % data
    #webbrowser.open(data)
    ## use gnome-open, less Pythonic, but uses current GNOME browser
    os.system("gnome-open '%s'" % data)

def url_button(artist, album, site, tooltips, album_type=0):

    # Create a new button
    button = gtk.Button()
    button.set_relief(gtk.RELIEF_NONE)

    site_name, baseurl_artist, baseurl_album, escape, both_for_album = site_list[site]

    # Generate URL
    if album_type:
        if both_for_album:
            url = baseurl_album % (string.replace(artist, ' ', escape), string.replace(album, ' ', escape))
        else:
            url = baseurl_album % string.replace(album, ' ', escape)
    else:
        url = baseurl_artist % string.replace(artist, ' ', escape)

    # Set the tooltip
    tooltips.set_tip(button, url, tip_private=None)
    
    # Connect the "clicked" signal of the button to our callback
    button.connect("clicked", callback, url)
    
    # Create box for label
    box1 = gtk.HBox(False, 0)
    box1.set_border_width(1)
        
    # Create a label for the button
    label = gtk.Label()

    # Create label text
    label_text = "Lookup on %s" % (site_name)
    label.set_markup('<u><span foreground="blue">' + label_text + '</span></u>')
    # Pack the label into the box
    box1.pack_start(label, False, False, 3)
    
    label.show()

    # Pack and show all our widgets
    button.add(box1)
    
    box1.show()
    button.show()

    return button

class BrowserWindow(gtk.Window):

    def __init__(self, db, entry, album_type=0):

        # use tooltips
        tooltips = gtk.Tooltips()
        
        gtk.Window.__init__(self)
        #self.set_border_width(12)
        
	title = db.entry_get(entry, rhythmdb.PROP_TITLE)
	artist = db.entry_get(entry, rhythmdb.PROP_ARTIST)
        album = db.entry_get(entry, rhythmdb.PROP_ALBUM)
        year = db.entry_get(entry, rhythmdb.PROP_DATE)

        if album_type:
            self.set_title("Album Information")
        else:
            self.set_title("Artist Information")
        #vbox = gtk.VBox(spacing=12)
        vbox = gtk.VBox()

        the_label = gtk.Label()

        if album_type:
            the_label.set_markup("<big><b><i>%s</i></b></big>" % album)
        else:
            the_label.set_markup("<big><b>%s</b></big>" % artist)

        # generate buttons
        button_list = []
        for site in site_list.keys():
            button = url_button(artist, album, site, tooltips, album_type)
            button_list.append(button)
        
        # close button
	close = gtk.Button(stock=gtk.STOCK_CLOSE)

	close.connect('clicked', lambda w: self.destroy())

        vbox.pack_start(the_label)
        bbox = gtk.VButtonBox()

        for button in button_list:
            bbox.pack_start(button)
        bbox.pack_start(close)
        vbox.pack_start(bbox, expand=False)

        self.add(vbox)
        ##self.set_default_size(400, 300)
        self.show_all()

ui_str = """
<ui>
  <popup name="BrowserSourceViewPopup">
    <separator/>
    <menuitem name="ViewArtistInfo" action="ViewArtistInfo"/>
    <menuitem name="ViewAlbumInfo" action="ViewAlbumInfo"/>
  </popup>
  <popup name="PlaylistViewPopup">
    <separator/>
    <menuitem name="ViewArtistInfo" action="ViewArtistInfo"/>
    <menuitem name="ViewAlbumInfo" action="ViewAlbumInfo"/>
  </popup>
  <popup name="AutoPlaylistSourcePopup">
    <separator/>
    <menuitem name="ViewArtistInfo" action="ViewArtistInfo"/>
    <menuitem name="ViewAlbumInfo" action="ViewAlbumInfo"/>
  </popup>
  <popup name="QueueSidebarViewPopup">
    <separator/>
    <menuitem name="ViewArtistInfo" action="ViewArtistInfo"/>
    <menuitem name="ViewAlbumInfo" action="ViewAlbumInfo"/>
  </popup>
  <popup name="QueuePlaylistViewPopup">
    <separator/>
    <menuitem name="ViewArtistInfo" action="ViewArtistInfo"/>
    <menuitem name="ViewAlbumInfo" action="ViewAlbumInfo"/>
  </popup>
</ui>

"""

class ArtistInfoDisplayPlugin(rb.Plugin):

    def __init__ (self):
	rb.Plugin.__init__ (self)
	self.window = None

    def activate (self, shell):
        self.action_group = gtk.ActionGroup ('ArtistInfoPluginActions')
        
	action = gtk.Action ('ViewArtistInfo', _('Artist Info'),
			     _('Display information for the selected artist'),
			     'rb-artist-info')
	action.connect ('activate', self.show_info, shell, 0)
	self.action_group.add_action (action)

	action = gtk.Action ('ViewAlbumInfo', _('Album Info'),
                              _('Display information for the selected album'),
                              'rb-album-info')
	action.connect ('activate', self.show_info, shell, 1)
	self.action_group.add_action (action)
    	
    	uim = shell.get_ui_manager ()
	uim.insert_action_group (self.action_group, 0)
	self.ui_id = uim.add_ui_from_string (ui_str)
	uim.ensure_update ()

    def deactivate (self, shell):
    	
	uim = shell.get_ui_manager()
	uim.remove_ui (self.ui_id)
	uim.remove_action_group (self.action_group)

	self.action = None
	self.action_group = None

	if self.window is not None:
	    self.window.destroy ()

    def show_info (self, action, shell, album_type):

	if self.window is not None:
	    self.window.destroy ()

	db = shell.get_property ("db")
	sp = shell.get_player ()
        selected_source = shell.get_property("selected-source")
        ev = selected_source.get_entry_view()

        # take first entry in list
	entry = ev.get_selected_entries()[0]
	if entry is not None:
	    self.window = BrowserWindow(db, entry, album_type=album_type)


