#!/usr/bin/python
#
#	released under the terms of the GPL v 2.0 (or later, at your opinion)
#	(c) 2005,2006 Roland Lezuo <roland.lezuo@chello.at>
#

__author__ = "Roland Lezuo <roland.lezuo@chello.at>"

import logging
logger = logging.getLogger("sgf-thumbnailer")

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


# 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


# implements an empty game
class NoneGame:
	def get_white_stones(self):
		return []
	def get_black_stones(self):
		return []
	def get_metadata(self):
		return gnomego.sgfparser.SGFGameMeta()

# 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:
			parser = gnomego.sgfparser.SGFParser()
			parser.parseString(bytes)
			# build GnomeGoGame and let it step through the whole game
			logger.info("Parsed data")
			self._game = gnomego.sgfparser.GnomeGoGame(parser.getSGFGame(0))
			while self._game.step(): 
				pass
		except Exception, e:
			logger.critical("Could not read data")
			logger.critical('Game.__init__:' + str(e))
			self._game = NoneGame()

	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 self._game.get_move_history()
	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
		logger.critical('exception, opening URI')
		return False

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

	logger.debug('Read: ' + str(source_bytes))

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

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

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

	logger.debug('creating pango_ctx')
	display = gtk.gdk.Display(':0.0')	#FIXME
	#hmm they simply renamed that one, try both names
	try:
		pango_ctx = gtk.gdk.pango_context_get_for_screen(display.get_default_screen())
	except:
		pango_ctx = gtk.gdk.gdk_pango_context_get_for_screen(display.get_default_screen())
	logger.debug('have a pango ctx')


	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, pango_ctx, pref.installed_prefix)
	try:
		board.set_background_color(gtk.gdk.parse_color(boardcolor))
	except:
		pass
	board.set_background_image(boardimg)
	# we want the last move to be marked 
	print game.get_move_history()["last"]
	board.mark_stone(game.get_move_history()["last"])
	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__':
	if os.getenv("GNOMEGO_DEBUG") != None:
		logging.basicConfig(level=logging.DEBUG)
	else:
		logging.basicConfig()

	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)
