#!/usr/bin/python
#author jay@socialistsoftware.com
#web http://www.socialistsoftware.com/
#license GPL http://www.gnu.org/copyleft/gpl.html

import pygtk ; pygtk.require('2.0')
import os, sys, string, gtk, gtk.glade
import gnome, gnome.ui, gobject, popen2, string

datadir = "/usr/share/gzinc/"    # set this to whatever directory you have installed the waiconfig.glade and ss_logo.gif files.
LOGO_FILE = datadir + 'ss_logo.jpg'
COPYRIGHT = 'Jay Graves (c) 2003'
VERSION = '0.06'
NAME = 'gzinc'
COMMENTS = 'a frontend for the zinc emulator'
AUTHORS = ['Jay Graves <jay@socialistsoftware.com>']

gnome.init(NAME,VERSION)

global gameList, gameId, gameName, settingsList, propWindow, paramList, widget_tree1, settingsFile, verifyWindow
settingsFile = os.path.expanduser("~") + "/.gZinc.cfg"
settingsList = {}
###################################################################################
#paramList holds a dictionary of all the widget names and the type of widget it is#
#widget type 1 = textField : widget type 0 = checkBox				  #
###################################################################################
paramList = {}
paramList['zincBinaryLocation'] = 1
paramList['romsDir'] = 1
paramList['config'] = 1
paramList['controller'] = 1
paramList['controllerConfig'] = 1
paramList['renderer'] = 1
paramList['rendererConfig'] = 1
paramList['soundFilter'] = 0
paramList['slowGeometry'] = 0
paramList['sound'] = 0
paramList['surroundLiteEnable'] = 0
paramList['stereoExciter'] = 0
paramList['soundFilterCutoff'] = 1
paramList['shotsDir'] = 1

def showAbout(widget):
	#shouldn't the about window get the appName and Version #
	#from the gnome.init ???
	#gzincAbout1 = gtk.glade.XML(datadir + "gzinc.glade", "gzincAbout")
	pixbuf = gtk.gdk.pixbuf_new_from_file(LOGO_FILE)
	copyright = unicode(COPYRIGHT, "latin-1").encode("utf8")
	gnome.ui.About(NAME, str(VERSION), copyright, COMMENTS, AUTHORS,logo_pixbuf=pixbuf).show()

def printStatus(message):
	pass
	#appbar1.push(message)

def playGame(widget):
	global settingsList
	if settingsList.has_key('gameName'):
		printStatus("Launching " + settingsList['gameName'])
		launchStr = settingsList['zincBinaryLocation']
		launchStr = launchStr + " " + `settingsList['gameId']`
		launchStr = launchStr + " --roms-directory=" + settingsList['romsDir']
		if settingsList['config'] <> '':
			launchStr = launchStr + ' --use-config-file=' + settingsList['config']
		if settingsList['renderer'] <> '':
			launchStr = launchStr + ' --renderer=' + settingsList['renderer']
		if settingsList['rendererConfig'] <> '':
			launchStr = launchStr + ' --use-renderer-cfg-file=' + settingsList['rendererConfig']
		if settingsList['controller'] <> '':
			launchStr = launchStr + ' --controller=' + settingsList['controller']
		if os.path.isfile(`settingsList['gameId']` + '.cfg'):
			launchStr = launchStr + ' --use-controller-cfg-file=' + settingsList['gameId'] + '.cfg'
			print '!!! using custom controller config file ' +  settingsList['gameId'] + '.cfg'
		elif settingsList['controllerConfig'] <> '':
			launchStr = launchStr + ' --use-controller-cfg-file=' + settingsList['controllerConfig']
		if settingsList['sound'] == 0:
			launchStr = launchStr + " --use-sound=no"
		if settingsList['soundFilter'] == 1:
			launchStr = launchStr + " --sound-filter-enable=yes"
		if settingsList['surroundLiteEnable'] == 1:
			launchStr = launchStr + " --sound-surround-lite-enable=yes"
		if settingsList['slowGeometry'] == 0:
			launchStr = launchStr + " --use-slow-geometry=no"
		if settingsList['stereoExciter'] == 1:
			launchStr = launchStr + " --sound-stereo-exciter=yes"
		if settingsList['soundFilterCutoff'] != '':
			launchStr = launchStr + " --sound-filter-cutoff=" + settingsList['soundFilterCutoff']
			
		print launchStr
		os.popen(launchStr)

def getSettings():
	global settingsList, paramList, settingsFile
	#get the settings from the old config file and convert it to the new format
	if os.path.isfile(os.path.expanduser("~") + "/.gzinc.cfg"):
		oldInputFile = open(os.path.expanduser("~") + "/.gzinc.cfg", "r")
		oldSettings = oldInputFile.readlines()
		for oldSetting in oldSettings:
			y = string.split(oldSetting, ' = ')
			if y[0][:-1] != '[zincInfo]':
				if len(y) == 2:
					settingsList[y[0]] = y[1][:-1]
					if y[1][:-1] == '0' or y[1][:-1] =='1':
						settingsList[y[0]] = eval(y[1][:-1])
		print settingsList
		settingsList['zincBinaryLocation'] = settingsList['zincbinarylocation']
		settingsList['shotsDir'] = settingsList['shotsdir']
		settingsList['romsDir'] = settingsList['romsdir']
		settingsList['controllerConfig'] = settingsList['controllerconfig']
		settingsList['stereoExciter'] = settingsList['stereoexciter']
		settingsList['rendererConfig'] = settingsList['rendererconfig']
		settingsList['surroundLiteEnable'] = settingsList['surroundliteenable']
		settingsList['soundFilter'] = settingsList['soundfilter']
		settingsList['soundFilterCutoff'] = settingsList['soundfiltercutoff']
		settingsList['slowGeometry'] = settingsList['slowgeometry']
		populateGameList('crap')
	if os.path.isfile(settingsFile):
		inputFile = open(settingsFile, "r")
		theSettings = inputFile.readlines()
		for setting in theSettings:
			x = string.split(setting,',')
			settingsList[x[0]] = x[1][:-1]
			if x[1][:-1] == '0' or x[1][:-1] == '1':
				settingsList[x[0]] = eval(x[1][:-1])
		if settingsList['zincBinaryLocation'] <> "":
			settingsList['zincBinaryLocation'] = settingsList['zincBinaryLocation']
			populateGameList('doesnt matter')

def saveSettings(widget):
	global settingsList, propWindow, paramList, settingsFile
	printStatus("Settings Saved")
	for param in paramList.keys():
		if paramList[param] == 1:
			settingsList[param] = propWindow.get_widget(param).get_text()
		else:
			settingsList[param] = propWindow.get_widget(param).get_active()
	thePropWindow = propWindow.get_widget("propertybox1")
	thePropWindow.hide()
	Output = open(settingsFile, 'w')
	outputString = ''
	for setting in settingsList.keys():
		if settingsList[setting] == 0 or settingsList[setting] == 1 or setting == 'gameId':
			outputString = outputString + setting + ',' + `settingsList[setting]` + '\n'
		else:
			outputString = outputString + setting + ',' + settingsList[setting] + '\n'
	Output.write(outputString)
	Output.close()
	if os.path.isfile(os.path.expanduser("~") + "/.gzinc.cfg"):
		os.popen("rm " + os.path.expanduser("~") + "/.gzinc.cfg")
		print "deleted old config file"

def selectGame(selection):
	global settingsList
	sel = selection.get_selected()
	if sel:
		model, iter = sel
		module = model.get_value(iter, 1)
		settingsList['gameId'] = model.get_value(iter, 0)
		settingsList['gameName'] = model.get_value(iter, 1)
	
	global settingsList, widget_tree1
	noteBook = widget_tree1.get_widget("notebook1")
	imageBox = widget_tree1.get_widget("pixmap1")
	if settingsList.has_key('shotsDir'):
		imageBox.set_from_file(settingsList['shotsDir'] + `settingsList['gameId']` + '.jpg')
#		imageBox.load_file(settingsList['shotsDir'] + settingsList['gameId'] + '.jpg')

def populateGameList(widget):
	global settingsList
	global gameListModel

	gameListModel = gtk.ListStore(gobject.TYPE_INT,gobject.TYPE_STRING)
	
	theGamesFile = os.popen(settingsList['zincBinaryLocation'] + ' --list-games', 'r')
	pass
	theGames = theGamesFile.read()
	theGames = string.split(theGames, '\n')
	for x in theGames[1:]:
		string.strip(x)
		gameId = x[:4]
		gameName = x[4:]
		if gameId <> 'Zinc':
			if string.strip(gameId) <> '':
				iter = gameListModel.append()
				gameListModel.set_value(iter, 0, string.atoi(gameId))
				gameListModel.set_value(iter, 1, gameName)
	
	gameList.set_model(gameListModel)
	selection = gameList.get_selection()
	selection.set_mode('single')
	#col = gtk.TreeViewColumn("ID", gtk.CellRendererText(), text=0)
	#col.set_sort_column_id(0)
	#gameList.append_column(col)
	col = gtk.TreeViewColumn("Game Name", gtk.CellRendererText(), text=1)
	col.set_sort_column_id(1)
	gameList.append_column(col)
	selection.connect('changed',selectGame)

def showProperties(widget):
	global settingsList, propWindow, paramList
	propWindow = gtk.glade.XML(datadir + "gzinc.glade","propertybox1")
	propWindow.signal_autoconnect(handler_dictionary)
	if settingsList <> {}:
		for param in paramList.keys():
			if settingsList.has_key(param):
				if paramList[param] == 1:
					propWindow.get_widget(param).set_text(settingsList[param])
				else:
					propWindow.get_widget(param).set_active(settingsList[param])

def exitProperties(widget):
	global propWindow
	propWindow.hide()

def verifyRom(widget):
	global verifyWindow, settingsList
	verifyWindow = gtk.glade.XML(datadir + "gzinc.glade","verifyWindow")
	verifyWindow.signal_autoconnect(handler_dictionary)
	verifyCall = settingsList['zincBinaryLocation'] + ' ' + `settingsList['gameId']` + ' --verify --roms-directory=' + settingsList['romsDir']
	theCall = popen2.popen3(verifyCall, 1)
	verifyText = theCall[2].read()
	theBox = verifyWindow.get_widget('verifyTextBox')
	if verifyText == "":
		theBox.set_text('Your rom is valid :)')
	else:
		theBox.set_text(verifyText)

def verifyOkClicked(widget):
	global verifyWindow
	theWindow = verifyWindow.get_widget("verifyWindow")
	theWindow.hide()

handler_dictionary = {"on_exit1_activate" : gtk.mainquit,
	"on_about1_activate" : showAbout,
	"playGame" : playGame,
	"on_gameList_select_row" : selectGame,
	"on_preferences1_activate" : showProperties,
	"saveConfig" : saveSettings,
	"on_getGameList_clicked" : populateGameList,
	"gtk_widget_destroy" : exitProperties,
	"on_verify_clicked" : verifyRom,
	"on_verifyOk_clicked" : verifyOkClicked}

widget_tree1 = gtk.glade.XML(datadir + "gzinc.glade", "gzincMain")
widget_tree1.signal_autoconnect(handler_dictionary)
appbar1 = widget_tree1.get_widget("appbar1")
gameList = widget_tree1.get_widget("gameList")

getSettings()
gtk.main()
