#!/usr/bin/env python

# -*- coding: utf8 -*- 

#***********************************************************************
# pysycache : a program for learn to use the mouse
# Copyright (C) 2005-2007 Vincent DEROO (vincent.pysycache@free.fr) 
# 
# This program is free software; you can redistribute it and/or 
# modify it under the terms of the GNU General Public License 
# as published by the Free Software Foundation; either version 2 
# of the License, or (at your option) any later version. 
# 
# This program is distributed in the hope that it will be useful, 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. 
# 
# You should have received a copy of the GNU General Public License 
# along with this program; if not, write to the Free Software 
# Foundation, Inc. : 
# 51 Franklin Street, Fifth Floor, Boston, MA02110-1301, USA
#***********************************************************************



#*******************************************************************************
# Importation des modules
#*******************************************************************************
import sys
import getopt, string
import random
import time
import locale

import random
import os.path
import pygame
from pygame.locals import *

import const
import datas
from pysyclasses import *
import pysymenu
import pysyselect
import pysyadmin









#*******************************************************************************
# Main of the program                                                          #
# parameters    typfull = 0 : in window                                        #
#                       = 1 : fullscreen                                       #
#*******************************************************************************
def main(typfull):
	random.seed()
	consoleadmin = 0

	#----------------- recuperation de l'encodage des console ------------------
	const.GConsoleLocale = sys.stdout.encoding
	datas.DebugMessage("")
	datas.DebugMessage("Console encoding : %s " % const.GConsoleLocale)

	datas.DebugMessage("")
	datas.DebugMessage("Directory of application : %s " % const.GRepPysycache)

	#----------------- recuperation du repertoire de l'application -------------
	str = os.path.abspath(sys.argv[0])
	(RepPysycacheTmp, filename) = os.path.split(str)
	const.GRepPysycache = RepPysycacheTmp.decode(const.GConsoleLocale)


	#lecture du fichier de configuration de pysycache
	ReadConfigPysycache()

	if const.GAdmin == 1:
		#mode administration
		pysyadmin.ShowWindow(typfull)
	else:
		#verification de l'existence des repertoires necessaires a pysycache
		try:
			if const.GPysyUserMode == 1:
				if os.path.exists(const.GRepUsersPysycache) == False:
					datas.DebugMessage("")
					datas.DebugMessage("the directory of users ( %s ) doesn't exist !" %const.GRepUsersPysycache)
					os.makedirs(const.GRepUsersPysycache)

			if os.path.exists(const.GRepScores) == False:
				datas.DebugMessage("")
				datas.DebugMessage("the directory of scores ( %s ) doesn't exist !" %const.GRepScores)
				os.makedirs(const.GRepScores)

			myrep = os.path.join(const.GRepScores, unicode("themes-buttons"))
			if os.path.isdir(myrep) == False:
				os.makedirs(myrep)
			myrep = os.path.join(const.GRepScores, unicode("themes-click"))
			if os.path.isdir(myrep) == False:
				os.makedirs(myrep)
			myrep = os.path.join(const.GRepScores, unicode("themes-move"))
			if os.path.isdir(myrep) == False:
				os.makedirs(myrep)
			myrep = os.path.join(const.GRepScores, unicode("themes-dblclick"))
			if os.path.isdir(myrep) == False:
				os.makedirs(myrep)
			myrep = os.path.join(const.GRepScores, unicode("themes-puzzle"))
			if os.path.isdir(myrep) == False:
				os.makedirs(myrep)

		except  Exception, err:
			print ""
			print ""
			print "*************************************************************"
			print "*"
			print '*           Error in directories creation : ', err
			print "*"
			print "*************************************************************"

		if const.GPysyUserMode == 0:
			#un joueur par utilisateur machine
			const.GRepPersoUser = os.path.join(os.path.expanduser("~"), "pysycache")
			pysymenu.ShowWindow(typfull)
		elif const.GPysyUserMode == 1:
			#plusieurs joueur par utilisateur machine
			pysyselect.ShowWindow(typfull, 0)
		else:
			#le fichier de definition de pysycache n'a pas pu etre lu : on force l'administration
			datas.DebugMessage("Start admin mode")
			consoleadmin = 1
			pysyadmin.ShowWindow(typfull)

	screen = pygame.display.get_surface()

	#-------------------------------- fin du jeu -------------------------------
	const.Gbackground_image, background_rect = datas.Load_image("images", "fond4.png")
	datas.ShowTransitionOfTheme(const.GDureeTransition, "fond4.png")
	pygame.time.delay(1000)
	const.Gbackground_image, background_rect = datas.Load_image("images", "fond5.png")
	datas.ShowTransitionOfTheme(const.GDureeTransition, "fond5.png")

	#------------------ affichage des credits ------------------------
	datas.ShowCreditsOfPySyCache(consoleadmin)




#*******************************************************************************
# Read the configuration file for the pysycache application                    #
# the configuration file is in unicode format                                  #
#*******************************************************************************
def ReadConfigPysycache():
	filename = os.path.join("/", "etc", "pysycache", 'pysycache.dfg')

	if os.path.isfile(filename):
		pass
	else:
		filename = os.path.join("etc", "pysycache", 'pysycache.dfg')

	#lecture du fichier de definition
	datas.DebugMessage("")
	datas.DebugMessage("Reading the .dfg file of pysycache... %s" % filename)

	if os.path.isfile(filename):
		f = open(filename, 'r')
		lignes  = f.readlines()
		for lig in lignes:
			lig = lig.strip()
			lig = lig.split('=')

			if len(lig) == 0:
				continue

			if string.upper(lig[0]) == 'USER' :
				#the type of user identification
				const.GPysyUserMode = int(lig[1])

			if string.upper(lig[0]) == 'SCORE' :
				#the type of user identification
				const.GRepScores = lig[1].decode("utf-8")

			if string.upper(lig[0]) == 'REPUSER' :
				#the directory of the users
				const.GRepUsersPysycache = lig[1].decode("utf-8")

		f.close()
	else:
		datas.DebugMessage("")
		datas.DebugMessage("dfg file of pysycache not found...")
		const.GPysyUserMode = 999
		const.GRepScores = ""
		const.GRepUsersPysycache = ""

	datas.DebugMessage("User management  %i " % const.GPysyUserMode)
	datas.DebugMessage("Scores directory %s " % const.GRepScores )
	datas.DebugMessage("Users directory  %s " % const.GRepUsersPysycache)



#*******************************************************************************
# Programme principal
#*******************************************************************************

#valeur par defaut
#const.GWithFullScreenInit = 1
#const.GWithSoundInit = 1
const.GWithCredits = 1
const.GWithHelp = 1
const.GDebug = 0
const.GAdmin = 0



# analyse des parametres passes en arguement
for opt in sys.argv:
	if const.GDebug == 1:
		print "option : ", opt

	if opt == '-nf':
		const.GPrefUserFromOptions.FullScreen = 0
	if opt == '-wf':
		const.GPrefUserFromOptions.FullScreen = 1
	if opt == '-ns':
		const.GPrefUserFromOptions.Sound = 0
		const.GWithSound = 0
	if opt == '-ws':
		const.GPrefUserFromOptions.Sound = 1
		const.GWithSound = 1
	if opt == '-nc':
		const.GWithCredits = 0
	if opt == '-nh':
		const.GWithHelp = 0
	if string.upper(opt[0:6]) == "-LANG=":
		const.GPrefUserFromOptions.Lang = opt[6:11]

	if string.upper(opt[0:6]) == "-FONT=":
		const.GPrefUserFromOptions.FontName = opt[6:]

	if opt == '-debug':
		const.GDebug = 1
		print "Mode debug"
	if opt == '-admin':
		const.GAdmin = 1

	if opt == '-h':
		datas.help_message()
	if opt == '--help':
		datas.help_message()
	if opt == '--version':
		print 'pysycache version 3.1'
		sys.exit(0)
	if opt == '--python-version':
		print 'Python '+ sys.version
		sys.exit(0)



#lancement de la boucle principale
if __name__ == '__main__': 
	main(const.GPrefUserFromOptions.FullScreen)
