#!/usr/bin/python2.4

import sys
import posix
import gnomevfs
import os, tempfile
import gnomego.board
import gnomego.sgfparser
import gnomego.preferences
import gtk
import gconf


# argv is supposed to look like:
# argv[0] == prognam
# argv[1] == size of target image
# argv[2] == source sgf file, as gnomevfs URI
# argv[3] == target file to be written

def debug(str):
	print str
	return
	f =  file ("/tmp/sgf.log", "a+")
	f.write(str)
	f.write('\n')
	f.close()


# implementes the absolutely necessary methods to draw the game
# some code is duplicated from gnomego, which is somewhat suboptimal
class Game:
	def __init__(self, bytes):
		self._parser = gnomego.sgfparser.SGFParser()
		try:
			success, res, nxt = self._parser.parse(bytes)
			if success:
				# build GnomeGoGame and let it step through the whole game
				self._game = gnomego.sgfparser.GnomeGoGame(res)
				while self._game.step(): 
					pass
			else:
				raise "foo"
		except Exception, e:
			debug('excpetion:' + str(e))
			self._w = []
			self._b = []
			self._s = 19

	def get_white_stones(self):
		return self._game.get_white_stones()
	def get_black_stones(self):
		return  self._game.get_black_stones()
	def get_move_history(self):
		return {}
	def get_captures(self):
		return ''
	def get_size(self):
		return self._game.get_metadata().size

def main():
	try:
		global source
		source = gnomevfs.Handle(sys.argv[2])
	except:
		# something's wrong with the URI
		debug('exception, opening URI')
		return False

	source_size = source.get_file_info().size
	source_bytes = source.read(source_size)
	
	if (len(source_bytes) != source_size):
		debug('source_bytes != source_size')
		return False

	debug('READ:')
	debug(source_bytes)

	pref = gnomego.preferences.GnomeGoPref()
		
	boardimg = pref.get_string('boardimg')
	boardcolor = pref.get_string('boardcolor')

	game = Game(source_bytes)
	debug('after game')
	size = int(game.get_size())
	scale= 1.0

	(x,y) = gnomego.board.get_size(size, scale)

	cmap = gtk.gdk.colormap_get_system()
	pixmap = gtk.gdk.Pixmap(None, x, y, cmap.get_visual().depth)
	pixmap.set_colormap(cmap)
	board = gnomego.board.Board(pixmap, game, size, scale, False, False, False, None, pref.installed_prefix)
	try:
		board.set_background_color(gtk.gdk.parse_color(boardcolor))
	except:
		pass
	board.set_background_image(boardimg)
	board.redraw()

	pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, *board.get_size())
	pixbuf = pixbuf.get_from_drawable(pixmap, cmap, 0, 0, 0, 0, -1, -1)

	scale_pixbuf = pixbuf.scale_simple(int(sys.argv[1]), int(sys.argv[1]), gtk.gdk.INTERP_HYPER)
	scale_pixbuf.save(sys.argv[3], 'png')

	return True
	
if __name__ == '__main__':
	debug("thungb")
	if main():
		sys.exit(0)
	else:
		# something went wrong if we are here
		print "Usage: sgf-thumbnailer SIZExSIZE gnomevfs:/source gnomevfs:/target"
		sys.exit(-1)
