# Bryan Schumaker (04 / 23 / 2011)

import gtk
from ocarina import fsselect
from libsaria import sources

def find_new_width(buf, new_h):
	w = buf.get_width()
	h = buf.get_height()
	if h == 0:
		h = 1
	return int( (float(w) / float(h)) * new_h )

def _resize(img, new_h):
	buf = img.get_pixbuf()
	if buf == None:
		return
	new_w = find_new_width(buf, new_h)
	buf   = buf.scale_simple(new_w, new_h, gtk.gdk.INTERP_HYPER)
	if buf == None:
		return
	img.clear()
	img.set_from_pixbuf(buf)

def resize(img, new_h):
	if new_h == 0:
		return
	new_h = int(new_h)
	try:
		_resize(img, new_h)
	except Exception, e:
		print e


class FileImage(gtk.Image):
	def __init__(self):
		gtk.Image.__init__(self)
		self.path   = None
		self.height = 0
		self.set_has_tooltip(True)
		self.connect("query-tooltip", self.tooltip)
		self.show()

	def get_file(self):
		return self.path

	def set_image(self, path, height):
		if path != self.path:
			self.path   = path
			self.height = height
			self.set_from_file(path)
			resize(self, height)

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


class Image(gtk.EventBox):
	def __init__(self):
		gtk.EventBox.__init__(self)
		self.image = FileImage()
		self.add(self.image)
		self.connect("button-press-event", self.clicked)
		self.show()

		self.get_file  = self.image.get_file
		self.set_image = self.image.set_image

	def clicked(self, widget, event):
		if event.button != 1:
			return
		id = sources.get_cur_id()
		if id == -1:
			return
		path = fsselect.select_file("Select an image")
		if path == None:
			return
		try:
			self.set_image(path, self.image.height)
			sources.set_attr("art", path)
		except Exception, e:
			print e
