#!/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 pysyadminpysycache
import pysyselect


#*******************************************************************************
# 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)

			ShowTheHelpOnAdmin()

			const.GLstSouris.draw(screen)

			pygame.display.update()

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

			#recherche du bouton concerne
			for btn in TabBtnAdmin :
				if ( event0 >= btn.left ) & ( event0 <= btn.left + btn.largeur ) & ( event1 >= btn.top  ) & ( event1 <= btn.top + btn.hauteur ) :
					ok = 1
					#----------- show the correct window -----------------
					#mise a jour de la zone d'aide
					const.Gbackground_image.blit(Background_Restore, (300, 300), (300, 300, 370, 200))

					if const.GWithSound == 1 :
						if not pygame.mixer.get_init():
							print "Cannot load sound : pygame error : ", pygame.get_error()
						else:
							if pygame.mixer.music.get_busy :
								pygame.mixer.music.stop()

					if ( btn.id == 4) :
						#Quitter
						return 0
					elif ( btn.id == 18) :
						#gestion des utilisateurs de pysycache
						pysyselect.ShowWindow(0, 1)
						btn.LoadNormalPicture(Background_Restore)
					elif ( btn.id == 19) :
						#gestion de pysycache
						pysyadminpysycache.ShowWindow(0)
						btn.LoadNormalPicture(Background_Restore)
					break

			if ok == 1:
				const.Gbackground_image.blit(Background_Restore, (0, 0))
				for btn in TabBtnAdmin:
					btn.LoadNormalPicture(Background_Restore)
				screen.blit(const.Gbackground_image, (0, 0))
				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()


	return 1




#*******************************************************************************
#
#*******************************************************************************
def ShowTheHelpOnAdmin():
	#recherche du bouton menu concerne par un survol
	#pour afficher l'aide sur l'activite
	inarea = 999
	screen = pygame.display.get_surface()
	for btn in TabBtnAdmin:
		if ( const.GMaSourisCurrentPositionX >= btn.left ) & ( const.GMaSourisCurrentPositionX <= btn.left + btn.largeur ) & ( const.GMaSourisCurrentPositionY >= btn.top  ) & ( const.GMaSourisCurrentPositionY <= btn.top + btn.hauteur ) :
			#on est au dessus d'un bouton menu
			inarea = btn.id

			#peut on afficher l'image floutee ?
			if const.GBtnMenu != inarea:
				#on est actuellement en image normale et on passe en image floue
				#effacer l'ancien 
				for btnold in TabBtnAdmin:
					if btnold.id == const.GBtnMenu :
						#mise a jour de l'image
						btnold.LoadNormalPicture(Background_Restore)
						break

				const.GBtnMenu = btn.id
					
				#afficher les effets visuels et sonores d'un survol
				btn.LoadSecondPicture(Background_Restore)

				#on affiche l'aide
				btn.ShowHelpOfMenu(const.Gbackground_image)
			else:
				#on est deja en image floue : on ne fait rien
				pass
			break

	if inarea == 999:
		#on est pas au dessus d'un bouton menu
		#il faut remettre le bouton menu en normal
		if const.GBtnMenu == 999:
			#on est deja en bouton normal
			pass
		else:
			#on est en bouton flou : on passe a normal
			for btn in TabBtnAdmin:
				if btn.id == const.GBtnMenu:
					#mise a jour de l'image du bouton
					btn.LoadNormalPicture(Background_Restore)

					#mise a jour de la zone d'aide (effacement)
					const.Gbackground_image.blit(Background_Restore, (195, 301), (195, 301, 400, 220))
					screen.blit(Background_Restore, (195, 301), (195, 301, 400, 220) )

					break
			const.GBtnMenu = 999


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

	datas.InitializePreferences()

	#-------------------------  Initialise son ---------------------------------
	if const.GPrefUserFromOptions.Sound == 1:
		try:
			pygame.mixer.pre_init(44100, -16, 2, 2048)
#			pygame.mixer.init()
		except  Exception, err:
			const.GWithSound = 0
			const.GSoundError = 1
			print ""
			print ""
			print "*************************************************************"
			print "*"
			print '*           Error in sound initialization : ', err
			print "*"
			print "*************************************************************"
	else:
		const.GWithSound = 0

	#-------------------------  Initialise screen ------------------------------
	try:
		(nbtry, nbfail) = pygame.init()
		if nbfail != 0:
			const.GWithSound = 0
			const.GSoundError = 1
			datas.DebugMessage("Some errors occurs in pygame.init() : all sounds will be desactivated ")

		
	except  Exception, err:
		print ""
		print ""
		print "*************************************************************"
		print "*"
		print '*           Error in initialization : ', err
		print "*"
		print "*************************************************************"



	#whe hide the mouse for all the game
	pygame.mouse.set_visible(const.CACHE)

	#------------ recuperation de la valeur de la langue -----------------------
	datas.InitializeLang()

	#chargement du dictionnaire
	datas.LoadDicoLang()

	if const.GPrefUserFromOptions.FullScreen == 0:
		#mode fenetre
		screen = pygame.display.set_mode((800, 600))
		imgicone, img_rect = datas.Load_image("images", "pysycache-32x32.png")
		pygame.display.set_icon(imgicone)
	else:
		#mode plein ecran
		screen = pygame.display.set_mode((800, 600), FULLSCREEN)

	datas.DebugMessage("")
	if const.GDebug == 1:
		print "Information on display = ", pygame.display.Info()

	pygame.display.set_caption('PySyCache')

	#-------------------------- image vide de fond -----------------------------
	background_image, background_rect = datas.Load_image("images", "fond1.png")
	screen.blit(background_image, (0,0))
	pygame.display.update()

	#attende de 1/2 seconde
	pygame.time.delay(500)

	#musique de fond
	datas.Load_sound("sounds", "startup.ogg")

	#------------------ transition vers le titre du jeu ------------------------
	datas.ShowTransitionOfTheme(const.GDureeTransition, "fond2.png", 0)
	pygame.time.delay(1000)

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

	#----------------------------- liste des boutons ---------------------------
	const.GBtnMenu = 999
	TabBtnAdmin.append(BtnOfMenu("fond-admin.png", 18, 'menu-users1.png', 'menu-users.png', 490, 180)) 			#menu utilisateurs
	TabBtnAdmin.append(BtnOfMenu("fond-admin.png", 19, 'menu-adminpysy1.png', 'menu-adminpysy.png', 55, 240)) 	#menu config pysycache
	TabBtnAdmin.append(BtnOfMenu("fond-menu.png", 4, 'btn-quitter1.png', 'btn-quitter.png', 690, 545)) 			#menu quitter
	for btn in TabBtnAdmin:
		btn.visible = 1
		btn.LoadNormalPicture(Background_Restore)
	screen.blit(const.Gbackground_image, (0, 0))

	#------------------- changer la souris en main -------------------------
#	pygame.event.clear()
	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()
