# Bryan Schumaker (10/24/2010)
import libsaria
import gtk
gdk = gtk.gdk

sources = libsaria.sources
from libsaria import threads

lock = threads.get_mutex("album_art")

class Image(gtk.Image):
	def __init__(self):
		gtk.Image.__init__(self)
		self.show()

	def set_height(self, new_h):
		buf = self.get_pixbuf()
		if buf == None:
			return False
		w = buf.get_width()
		h = buf.get_height()
		if h == new_h:
			return False
		if h == 0:
			h = 1
		new_w = (float(w) / float(h)) * new_h
		if new_w <= 0 or new_h <= 0:
			return False

		buf = buf.scale_simple(int(new_w), int(new_h), gtk.gdk.INTERP_HYPER)
		if buf == None:
			return False
		self.set_from_pixbuf(buf)
		return True


class AlbumArtImage(Image):
	def __init__(self, size):
		Image.__init__(self)
		self.size = size
		self.file = None
		self.set("images/ocarina.png")
		self.set_has_tooltip(True)
		self.connect("query-tooltip", self.tooltip)
		self.connect("button-press-event", self.clicked)
		libsaria.event.invite("PRELOAD", self.preload)
		libsaria.event.invite("POSTGETART", self.set)
		libsaria.event.invite("POSTSETART", self.set_locked)

	def preload(self, *args):
		self.file = "images/ocarina.png"

	def clicked(self, widget, event):
		print widget, event

	def tooltip(self, image, x, y, keyboard, tip):
		image = gtk.Image()
		image.set_from_file(self.file)
		tip.set_icon(image.get_pixbuf())
		return True

	def set(self, file=None):
		gdk.threads_enter()
		self.set_locked(file)
		gdk.threads_leave()

	def set_locked(self, file=None):
		for i in xrange(2):
			self.file = file
			try:
				self.set_from_file(self.file)
				if self.set_height(self.size) == True:
					break
			except:
				pass
			file = "images/ocarina.png"

	def set_height(self, new_h):
		size = self.size_request()
		if size[1] == new_h:
			return
		return Image.set_height(self, new_h)


class AlbumArt(gtk.EventBox):
	def __init__(self, size=64):
		gtk.EventBox.__init__(self)
		self.image = AlbumArtImage(size)
		self.add(self.image)
		self.connect("button-press-event", self.clicked)
		self.show_all()

	def clicked(self, widget, event):
		if event.button != 1:
			return
		if sources.cur_lib_id == -1:
			return
		from ocarina import fsselect
		path = fsselect.file("Select an image")
		if path == None:
			return
		print "Selected file: %s" % path
		try:
			#self.image.set(path)
			sources.library.set_attr(sources.cur_lib_id, "art", path)
		except Exception, e:
			print e
			pass

