#!/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 datas
from pysyclasses import BtnOfMenu
from pysyclasses import MouseOfActivity
import const
import pysyihm

#marge image marge texte
#                  marge image marge valeur1
#lef1   64   mge1  mge2    32  mge3            mge4 | milieur de l'ecran
PREFLEFT1 = 20					#mge a gauche
PREFLEFT2 = 360		#720 / 2 
MGE1 = 10						#mge entre l'image et le texte
MGE2 = 20						#mge entre oui/non et le texte
MGE3 = 10
MGE4 = 5

 


#*******************************************************************************
# 
#*******************************************************************************
def ShowLevelInPreferences():
	""" gestion du choix du niveau de difficulte"""
	screen = pygame.display.get_surface()

	#recuperer la hauteur et faire un placement dynamique par rapport au centre 
	const.Gbackground_image.blit(Background_Restore, (180, 385), (180, 385, 120, 60))

	if const.GPrefUserTmp.Level == 0:
		datas.WriteTextInLang("NIV0", "Easy", const.Gbackground_image, 180, 385, 30)
	elif const.GPrefUserTmp.Level == 1:
		datas.WriteTextInLang("NIV1", "Medium", const.Gbackground_image, 180, 385, 30)
	else:
		datas.WriteTextInLang("NIV2", "Difficult", const.Gbackground_image, 180, 385, 30)
	screen.blit (const.Gbackground_image, (180, 385), (180, 385, 120, 60))


#*******************************************************************************
#
#*******************************************************************************
def ShowLangInPreferences():
	""" gestion du choix de la langue"""
	screen = pygame.display.get_surface()

	flagname = os.path.join(const.GRepPysycache, "lang", const.GPrefUserTmp.Lang, "flag.png").encode(const.GConsoleLocale)
	if os.path.isfile(flagname) == True:
		const.Gbackground_image.blit(Background_Restore, (210, 470), (210, 470, 100, 70))
		screen.blit(Background_Restore, (210, 470), (210, 470, 100, 70))
		imgflag = pygame.image.load(flagname).convert()
		#centrer dynamiquement le drapeau
		const.Gbackground_image.blit(imgflag, (210, 470))
		screen.blit(imgflag, (210, 470))


#*******************************************************************************
#
#*******************************************************************************
def ShowTransitInPreferences():
	""" gestion de la vitesse de transition"""
	screen = pygame.display.get_surface()

	#recuperer la hauteur et faire un placement dynamique par rapport au centre 
	const.Gbackground_image.blit(Background_Restore, (540, 370), (540, 370, 90, 60))

	datas.WriteTextInLang("XXX", str(const.GPrefUserTmp.Transition), const.Gbackground_image, 540, 385, 30)
	screen.blit (const.Gbackground_image, (540, 370), (540, 370, 90, 70))




#*******************************************************************************
# Event detection                                                              #
#*******************************************************************************
def DetectEvent():
	""" Traitement des evenements """
	for event in pygame.event.get():
		if event.type == QUIT:
			return 0
		elif event.type == KEYUP:
			if event.key == K_ESCAPE:
				return 0
		elif event.type == pygame.MOUSEMOTION:
			#*************** evenement deplacement de la souris ***************
			event0 = event.pos[0] 
			event1 = event.pos[1] 

			screen = pygame.display.get_surface()

			#redessin de la souris a sa position actuelle
			const.GMaSourisCurrentPositionX = event0 
			const.GMaSourisCurrentPositionY = event1 
			for o in const.GLstSouris.sprites():
				o.move(const.Gbackground_image)

			const.GLstSouris.draw(screen)

			pygame.display.update()
			
			return 1
		elif event.type == MOUSEBUTTONUP:
			#---------------------- on relache la souris -----------------------
			ok = 0
			event0 = event.pos[0] 
			event1 = event.pos[1] 

			screen = pygame.display.get_surface()  

			#------------------------ boutons de menus -------------------------
			for btn in TabBtnPreferences :
				if ( event0 >= btn.left ) & ( event0 <= btn.left + btn.largeur ) & ( event1 >= btn.top  ) & ( event1 <= btn.top + btn.hauteur ) :
					if ( btn.id == 14) :
						#Quitter
						return 0
					elif ( btn.id == 20) :
						#save the pysycache configuration
						const.GPrefUserTmp.Save()

						#chargement des nouvelles valeurs
						filenameuser = os.path.join(const.GRepPersoUser, "pysycacherc")
						const.GPrefUserInit.ReadConfigOfUser(filenameuser)
						datas.InitializePreferences()
						datas.InitializeLang()
						datas.LoadDicoLang()
					#----------------------- bouton du mode fenetre -------------------
					elif (btn.id == 11) :
						if const.GPrefUserTmp.FullScreen == 0:
							const.GPrefUserTmp.FullScreen  = 1
							btn.LoadNormalPicture(Background_Restore)
							for btn2 in TabBtnPreferences:
								if ( btn2.id == 12) :
									btn2.LoadNormalPicture(Background_Restore)
									break
							datas.Load_sound("sounds", "btncoche.ogg")
						else:
							const.GPrefUserTmp.FullScreen  = 0
							btn.LoadSecondPicture(Background_Restore)
							for btn2 in TabBtnPreferences:
								if ( btn2.id == 12) :
									btn2.LoadSecondPicture(Background_Restore, "btncoche.ogg")
									break
					elif (btn.id == 12) :
						if const.GPrefUserTmp.FullScreen == 0:
							const.GPrefUserTmp.FullScreen  = 1
							btn.LoadNormalPicture(Background_Restore)
							datas.Load_sound("sounds", "btncoche.ogg")
							for btn2 in TabBtnPreferences:
								if ( btn2.id == 11) :
									btn2.LoadNormalPicture(Background_Restore)
									break
						else:
							const.GPrefUserTmp.FullScreen  = 0
							btn.LoadSecondPicture(Background_Restore)
							for btn2 in TabBtnPreferences:
								if ( btn2.id == 11) :
									btn2.LoadSecondPicture(Background_Restore, "btncoche.ogg")
									break
					#----------------------- bouton du son -------------------
					elif (btn.id == 21):
						if const.GPrefUserTmp.Sound == 0:
							const.GPrefUserTmp.Sound  = 1
							btn.LoadNormalPicture(Background_Restore)
							datas.Load_sound("sounds", "btncoche.ogg")
							for btn2 in TabBtnPreferences:
								if ( btn2.id == 22) :
									btn2.LoadNormalPicture(Background_Restore)
									break
						else:
							const.GPrefUserTmp.Sound  = 0
							btn.LoadSecondPicture(Background_Restore)
							for btn2 in TabBtnPreferences:
								if ( btn2.id == 22) :
									btn2.LoadSecondPicture(Background_Restore, "btncoche.ogg")
									break
					elif (btn.id == 22):
						if const.GPrefUserTmp.Sound == 0:
							const.GPrefUserTmp.Sound  = 1
							btn.LoadNormalPicture(Background_Restore)
							datas.Load_sound("sounds", "btncoche.ogg")
							for btn2 in TabBtnPreferences:
								if ( btn2.id == 21) :
									btn2.LoadNormalPicture(Background_Restore)
									break
						else:
							const.GPrefUserTmp.Sound  = 0
							btn.LoadSecondPicture(Background_Restore)
							for btn2 in TabBtnPreferences:
								if ( btn2.id == 21) :
									btn2.LoadSecondPicture(Background_Restore, 'btncoche.ogg')
									break
					#----------------------- bouton de difficultes -------------------
					elif (btn.id == 31):
						#a gauche
						ok = 1
						if const.GPrefUserTmp.Level == 0:
							const.GPrefUserTmp.Level  = 2
						else:
							const.GPrefUserTmp.Level  = const.GPrefUserTmp.Level - 1
						ShowLevelInPreferences()
					elif (btn.id == 32):
						#a droite
						ok = 1
						if const.GPrefUserTmp.Level < 2:
							const.GPrefUserTmp.Level += 1
						else:
							const.GPrefUserTmp.Level = 0
						ShowLevelInPreferences()
					#------------------------- fleches de langue -----------------------
					elif (btn.id == 41):
						#a gauche
						ok = 1
						if const.GPrefUserLang == 0:
							const.GPrefUserLang  = len(const.GTabLang) - 1
						else:
							const.GPrefUserLang  = const.GPrefUserLang - 1
						#on affiche le drapeau
						const.GPrefUserTmp.Lang = const.GTabLang[const.GPrefUserLang]
						ShowLangInPreferences()
					elif (btn.id == 42):
						#a droite
						ok = 1
						if const.GPrefUserLang < len(const.GTabLang) - 1:
							const.GPrefUserLang += 1
						else:
							const.GPrefUserLang = 0
						#on affiche le drapeau
						const.GPrefUserTmp.Lang = const.GTabLang[const.GPrefUserLang]
						ShowLangInPreferences()
					#------------------------- fleches de transition -----------------------
					elif (btn.id == 51):
						#a gauche
						ok = 1
						if const.GPrefUserTmp.Transition != 0:
							const.GPrefUserTmp.Transition  = const.GPrefUserTmp.Transition - 1
						ShowTransitInPreferences()
					elif (btn.id == 52):
						#a droite
						ok = 1
						const.GPrefUserTmp.Transition += 1
						ShowTransitInPreferences()
					#------------------------------ fleches de logo --------------------
					elif (btn.id == 61):
						if (const.GPysyUserMode == 1) or (const.GAdmin == 1) :
							ok = 0
							#a gauche
							ok = 1
							if const.GIdxphoto > 0:
								const.GIdxphoto = const.GIdxphoto - 1
							else:
								const.GIdxphoto = len(const.GLstFaces) - 1
						const.GPrefUserTmp.LogoFile = const.GLstFaces[const.GIdxphoto]
						ShowLogoOfUser()
					elif (btn.id == 62):
						if (const.GPysyUserMode == 1) or (const.GAdmin == 1) :
							#image apres (dans le theme)
							if const.GIdxphoto < len(const.GLstFaces) - 1:
								const.GIdxphoto += 1
							else:
								const.GIdxphoto = 0

						const.GPrefUserTmp.LogoFile = const.GLstFaces[const.GIdxphoto]
						ShowLogoOfUser()
						break

			ok = 1

			#rafraichissement
			if ok == 1:
				const.GLstSouris.draw(screen)
				pygame.display.update()


	return 1


#*******************************************************************************
#
#*******************************************************************************
def SearchAllFaces(PhotoFile):
	const.GIdxphoto = 0
	const.GLstFaces[:] = []

	if (const.GPysyUserMode == 1) or (const.GAdmin == 1) :
		repertoire = os.path.join(const.GRepPysycache, "images", "faces")
		datas.DebugMessage("")
		datas.DebugMessage("Search all faces in %s " % repertoire)
		idx = 0
		strfaces = ''
		for nom in os.listdir(repertoire):
			datas.DebugMessage ("... found %s " % nom)
			const.GLstFaces.append(nom)
			strfaces = strfaces + ', ' + nom
			if nom == PhotoFile :
				const.GIdxphoto = idx
			idx += 1


#*******************************************************************************
#    
#*******************************************************************************
def ShowLogoOfUser():
#	obj2 = const.GTabUser[const.GSelectedUser][1]
#	username = obj2.name

	if (const.GPysyUserMode == 1) or (const.GAdmin == 1) :
		screen = pygame.display.get_surface()
#		#copie du nom de l'utilisateur
#		if username != "":
#			myfont = os.path.join(const.GRepPysycache, 'fonts', const.GFontName)
#			font = pygame.font.Font(myfont, 20)
#			textcolor = 46, 113, 169
#			text = font.render(unicode(username, const.GConsoleLocale), 1, textcolor).convert_alpha()
##		text = font.render(username, 1, textcolor).convert_alpha()
#			(larg, haut) = text.get_size()
#			const.Gbackground_image.blit(text, (480, 80))
#			screen.blit(text, (480, 240))

		imgtmp, recttmp = datas.Load_image("images", "fond-select.png")
		const.Gbackground_image.blit(imgtmp, (515, 150), (515, 150, 130, 190))
		imgtmp, recttmp = datas.Load_image("images", "img-user0.png")
		const.Gbackground_image.blit(imgtmp, (515, 150))
		filephoto = os.path.join(const.GRepPysycache, "images", "faces", const.GPrefUserTmp.LogoFile)
		if os.path.isfile(filephoto):
			imgtmp2, recttmp = datas.Load_image("images", filephoto, None, True)
			const.Gbackground_image.blit(imgtmp2, (515 + 17, 150 + 17))		#17 = (126 - 92 ) /2

		screen.blit(const.Gbackground_image, (515, 150), (515, 150, 130, 190))
		pygame.display.update((515, 150, 150, 190))




#*******************************************************************************
# Main of the program                                                          #
# parameters    typfull = 0 : in window                                        #
#                       = 1 : fullscreen                                       #
#*******************************************************************************
def ShowWindow(typfull, username = ""):
	global TabBtnPreferences 			#tableau des boutons de l'application
	TabBtnPreferences = []
	TabBtnPreferences[:]= []
	global Background_Restore

	screen = pygame.display.get_surface()

	datas.ShowTransitionOfTheme(const.GDureeTransition, "fond-preferences.png", 0)

	const.GPrefUserTmp.Sound = const.GPrefUserInit.Sound
	const.GPrefUserTmp.Lang = const.GPrefUserInit.Lang
	const.GPrefUserTmp.Level = const.GPrefUserInit.Level
	const.GPrefUserTmp.Transition = const.GPrefUserInit.Transition
	const.GPrefUserTmp.FullScreen = const.GPrefUserInit.FullScreen
	const.GPrefUserTmp.LogoFile = const.GPrefUserInit.LogoFile
	const.GPrefUserTmp.Fileofpreference = const.GPrefUserInit.Fileofpreference


	#----------------------- transition vers le menu ---------------------------
	const.Gbackground_image, background_rect = datas.Load_image("images", "fond-preferences.png")
	Background_Restore, background_rect = datas.Load_image("images", "fond-preferences.png")

	#---------- affichage des differentes sections des preferences -------------
	#titre
	datas.WriteTextInLang("PRF00", "Arrange your preferences", const.Gbackground_image, -1, 21, 40)

	#plein ecran
	imgtmp, rectmp = datas.Load_image("images", "btn-pref-fenetre.png")
	const.Gbackground_image.blit(imgtmp, (PREFLEFT1, 110))
	datas.WriteTextInLang("SCR", "Choice of the screen mode", const.Gbackground_image, PREFLEFT1 + 64 + MGE1, 100, 20)
	datas.WriteTextInLang("SCR1", "Fullscreen mode", const.Gbackground_image, PREFLEFT1 + 64 + MGE1 + MGE2 + 32 + MGE3, 140, 20)
	datas.WriteTextInLang("SCR2", "Window mode", const.Gbackground_image, PREFLEFT1 + 64 + MGE1 + MGE2 + 32 + MGE3, 180, 20)

	#son
	imgtmp, rectmp = datas.Load_image("images", "btn-pref-sons.png")
	const.Gbackground_image.blit(imgtmp, (PREFLEFT1, 230))
	datas.WriteTextInLang("SON", "Sound activation ?", const.Gbackground_image, PREFLEFT1 + 64 + MGE1, 220, 20)
	datas.WriteTextInLang("OUI", "Yes", const.Gbackground_image, PREFLEFT1 + 64 + MGE1 + MGE2 + 32 + MGE3, 260, 20)
	datas.WriteTextInLang("NON", "No", const.Gbackground_image, PREFLEFT1 + 64 + MGE1 + MGE2 + 32 + MGE3, 300, 20)

	#niveau
	imgtmp, rectmp = datas.Load_image("images", "btn-pref-niveaux.png")
	const.Gbackground_image.blit(imgtmp, (PREFLEFT1, 350))
	datas.WriteTextInLang("NIV", "Default", const.Gbackground_image, PREFLEFT1 + 64 + MGE1, 340, 20)

	#lang
	imgtmp, rectmp = datas.Load_image("images", "btn-pref-lang.png")
	const.Gbackground_image.blit(imgtmp, (PREFLEFT1, 450))
	datas.WriteTextInLang("LANG", "Choice of the menus language", const.Gbackground_image, PREFLEFT1 + 64 + MGE1, 440, 20)

	#vitesse transition
	imgtmp, rectmp = datas.Load_image("images", "btn-pref-transition.png")
	const.Gbackground_image.blit(imgtmp, (390, 350))
	datas.WriteTextInLang("TRANSIT", "Speed of transition", const.Gbackground_image, 460, 340, 20)

	Background_Restore.blit(const.Gbackground_image, (0,0))

#	obj2 = const.GTabUser[const.GSelectedUser][1]
#	username = obj2.name

	if (const.GPysyUserMode == 1) or (const.GAdmin == 1) :
		#copie du nom de l'utilisateur
		if username != "":
			myfont = os.path.join(const.GRepPysycache, 'fonts', const.GFontName).encode(const.GConsoleLocale)
			font = pygame.font.Font(myfont, 20)
			textcolor = 46, 113, 169
#			text = font.render(unicode(username, const.GConsoleLocale), 1, textcolor).convert_alpha()
#			text = font.render(username.decode(const.GConsoleLocale, "ignore"), 1, textcolor).convert_alpha()
			text = font.render(username, 1, textcolor).convert_alpha()
			(larg, haut) = text.get_size()
			const.Gbackground_image.blit(text, (480, 110))
			screen.blit(text, (480, 110))

	#logo de l'utilisateur
	ShowLogoOfUser()
	ShowLevelInPreferences()
	ShowLangInPreferences()
	ShowTransitInPreferences()

	screen.blit(const.Gbackground_image, (0, 0))

	#----------------------------- liste des boutons ---------------------------
	const.GBtnMenu = 999
	TabBtnPreferences[:]=[]
	TabBtnPreferences.append(BtnOfMenu("fond-admin-pysy.png", 14, 'btn-quitter-gd.png', 'btn-quitter.png', 710 - 20, 565 - 20)) 	#quitter
	TabBtnPreferences.append(BtnOfMenu("fond-admin-pysy.png", 20, 'btn-admin-save.png', 'btn-admin-save.png', 735, 10)) 			#enregistrer
	#-------------------------- gestion de la fenetre ------------------
	#mode fenetre
	TabBtnPreferences.append(BtnOfMenu("fond-admin-pysy.png", 11, 'cancel.png', 'apply.png', PREFLEFT1 + 64 + MGE1 + MGE2, 141) )			
	TabBtnPreferences.append(BtnOfMenu("fond-admin-pysy.png", 12, 'apply.png', 'cancel.png', PREFLEFT1 + 64 + MGE1 + MGE2, 181) )			
	#---------------------- gestion du son -------------------------------
	TabBtnPreferences.append(BtnOfMenu("fond-admin-pysy.png", 21, 'cancel.png', 'apply.png', PREFLEFT1 + 64 + MGE1 + MGE2, 261))
	TabBtnPreferences.append(BtnOfMenu("fond-admin-pysy.png", 22, 'apply.png', 'cancel.png', PREFLEFT1 + 64 + MGE1 + MGE2, 301))
	#-------------------------- fleches de difficultes -----------------------
	TabBtnPreferences.append(BtnOfMenu("fond-admin-pysy.png", 31, 'btn-prev.png', 'btn-prev.png', PREFLEFT1 + 64 + MGE1 + MGE2, 380))
	TabBtnPreferences.append(BtnOfMenu("fond-admin-pysy.png", 32, 'btn-next.png', 'btn-next.png', PREFLEFT1 + PREFLEFT2 - 32 - MGE4, 380))
	#--------------------------- fleches de langues --------------------------
	TabBtnPreferences.append(BtnOfMenu("fond-admin-pysy.png", 41, 'btn-prev.png', 'btn-prev.png', PREFLEFT1 + 64 + MGE1 + MGE2, 480))
	TabBtnPreferences.append(BtnOfMenu("fond-admin-pysy.png", 42, 'btn-next.png', 'btn-next.png', PREFLEFT1 + PREFLEFT2 - 32 - MGE4, 480))
	#--------------------------- fleches de vitesse de transition --------------------------
	TabBtnPreferences.append(BtnOfMenu("fond-admin-pysy.png", 51, 'btn-prev.png', 'btn-prev.png', PREFLEFT1 + PREFLEFT2 + MGE1 + 64 + MGE2, 380))
	TabBtnPreferences.append(BtnOfMenu("fond-admin-pysy.png", 52, 'btn-next.png', 'btn-next.png', 650, 380))
	#--------------------------- fleches de logo d'utilisateur --------------------------
	if (const.GPysyUserMode == 1) or (const.GAdmin == 1) :
		#nom de l'utilisateur
		TabBtnPreferences.append(BtnOfMenu("fond-admin-pysy.png", 61, 'btn-prev.png', 'btn-prev.png', PREFLEFT1 + PREFLEFT2 + MGE1 + 64 + MGE2, 180))
		TabBtnPreferences.append(BtnOfMenu("fond-admin-pysy.png", 62, 'btn-next.png', 'btn-next.png', 650, 180))
		SearchAllFaces(const.GPrefUserTmp.LogoFile)

	for btn in TabBtnPreferences:
		if (btn.visible == 1) : 
			if btn.id == 11:
				if const.GPrefUserTmp.FullScreen == 1:
					#plein ecran
					btn.LoadNormalPicture(Background_Restore)
				else:
					#
					btn.LoadNormalPicture(Background_Restore)
					btn.LoadSecondPicture(Background_Restore, 'btncoche.ogg')
			elif btn.id == 12 :
				if const.GPrefUserTmp.FullScreen == 1:
					btn.LoadNormalPicture(Background_Restore)
				else:
					btn.LoadNormalPicture(Background_Restore)
					btn.LoadSecondPicture(Background_Restore, 'btncoche.ogg')
			if btn.id == 21:
				if const.GPrefUserTmp.Sound == 1:
					#son
					btn.LoadNormalPicture(Background_Restore)
				else:
					#
					btn.LoadNormalPicture(Background_Restore)
					btn.LoadSecondPicture(Background_Restore, 'btncoche.ogg')
			elif btn.id == 22 :
				if const.GPrefUserTmp.Sound == 1:
					btn.LoadNormalPicture(Background_Restore)
				else:
					btn.LoadNormalPicture(Background_Restore)
					btn.LoadSecondPicture(Background_Restore, 'btncoche.ogg')
			else:
				btn.LoadNormalPicture(Background_Restore)
#			btn.LoadNormalPicture(Background_Restore)
		else:
			btn.ClearBackground(Background_Restore)

	screen.blit(const.Gbackground_image, (0, 0))


	#recherche des langues disponibles
	const.GTabLang[:] = []
	strnom = ''
	repertoire = os.path.join(const.GRepPysycache, "lang")
	for nom in os.listdir(repertoire):
		isrep = os.path.join(const.GRepPysycache, "lang", nom)
		if os.path.isdir(isrep):
			const.GTabLang.append(nom)
			strnom = strnom + ", " + nom
	datas.DebugMessage("")
	datas.DebugMessage("Found languages : %s " % strnom)

	#------------------- changer la souris en main -------------------------
	const.GLstSouris.empty()
	const.GLstSouris.add(MouseOfActivity(400, 300, "souris.png") )
	for o in const.GLstSouris.sprites():
		o.move(const.Gbackground_image)
	const.GLstSouris.draw(screen)
	pygame.display.update()
	pygame.event.clear()

	const.GTypeSouris = const.EVENT_JEU0

	#---------------------- entree dans la boucle principale -------------------
	running = 1
	while running:
		datas.Temporisation()

		#----------------- recherche des evt -----------------------------------
		running = DetectEvent()

		datas.ShowFPS()
