#!/usr/bin/env python

# -*- coding: utf8 -*- 

#***********************************************************************
# pysycache : a tool for learn to use the mouse
# Copyright (C) 2005-2006 Vincent DEROO (vincent.pysycache@free.fr)
#
# This tool is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library 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
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the Free
# Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#***********************************************************************



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

import random, os
import pygame
from pygame.locals import *
import glob

import datas
from datasclass import BtnMenu
import const
import pysymove
import pysyclick
import pysybuttons



DUREETRANSITION = 8



def ReadCreditOfDirectory(dirname):
	myfont = os.path.join(const.GRepPysycache, 'fonts', 'FreeSansBold.ttf' )
	font = pygame.font.Font(myfont, 20)	
	textcolor = 46, 113, 169

	repertoire = os.path.join(const.GRepPysycache, dirname)
	for nom in os.listdir(repertoire):
		#ne prendre que les repertoires
		isrep = os.path.join(repertoire, nom)
		if os.path.isdir(isrep):
			fichier = os.path.join(repertoire, nom, 'credits.txt')
			if os.path.isfile(fichier):
				screen = pygame.display.get_surface()
				screen.blit(Gbackground_image, (0,0))
				#afficher le contenu 
				f = open(fichier, 'r')
				lignes  = f.readlines()
				cptligne = 0;
				for j in lignes:
					j = j.strip()
					text = font.render(unicode(j, "utf-8"), 1, textcolor)
					screen.blit(text, (50, 60 + 20 * cptligne)) 
					cptligne = cptligne + 1
				f.close()

				pygame.display.flip()

			#attente de 3 secondes entre deux credits
			pygame.time.wait(3000) 




#*******************************************************************************
# Detection des evenements
#                                                                              #
#	self.listenKeys = { K_UP: self.MoveUp,
#	                    K_DOWN: self.MoveDown,
#	                    K_LEFT: self.SetVelocityLeft,
#	                    K_RIGHT: self.SetVelocityRight,
#	                    K_SPACE: self.MoveUp
#	                  }
#                                                                              #
#*******************************************************************************
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()
			screen.blit(Gbackground_image, (0,0))
			LstBtn.draw(screen)	

			#redessin de la souris a sa position actuelle
			screen.blit(GMaSouris, GMaSouris_position)

			GMaSouris_position.left = event0 
			GMaSouris_position.top = event1 

			#recherche du bouton menu
			inarea = 999
			for btn in LstBtn.sprites():
				if ( event.pos[0] >= btn.rect.left ) & ( event.pos[0] <= btn.rect.left + btn.largeur ) & ( event.pos[1] >= btn.rect.top  ) & ( event.pos[1] <= btn.rect.top + btn.hauteur ) :
					#on est dans la zone proche du 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
						const.GBtnMenu = btn.id

						datas.load_sound('sounds', 'btnmenu.wav')

						filename = os.path.join(const.GRepPysycache, 'images', btn.imagename + '1.png')
						imgtmp = pygame.image.load(filename)
						btn.image.blit(imgtmp, (btn.rect.left, btn.rect.top), (0, 0, btn.largeur, btn.hauteur))
						btn.image = imgtmp

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

			if inarea == 999:
				#on est loin d'un bouton : 
				#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 LstBtn.sprites():
						if btn.id == const.GBtnMenu:
							#mise a jour de l'image
							filename = os.path.join(const.GRepPysycache, 'images', btn.imagename + '.png')
							imgtmp = pygame.image.load(filename)
							btn.image.blit(imgtmp, (btn.rect.left, btn.rect.top), (0, 0, btn.largeur, btn.hauteur))
							btn.image = imgtmp

							#mise a jour de la zone d'aide (effacement)
							imgnuage, background_rect = datas.load_image('images', 'fond-menu.bmp')
							Gbackground_image.blit(imgnuage, (300, 300), (300, 300, 400, 220))

							break
					const.GBtnMenu = 999
			return 1
		elif event.type == MOUSEBUTTONDOWN:
			#*************************** evenement clic *************************
			ok = 0
			screen = pygame.display.get_surface()  

			#recherche du bouton concerne
			for obj in LstBtn.sprites() :
				if ( event.pos[0] >= obj.rect.left ) & ( event.pos[0] <= obj.rect.left + obj.largeur ) & ( event.pos[1] >= obj.rect.top  ) & ( event.pos[1] <= obj.rect.top + obj.hauteur ) :
					#----------- show the correct window -----------------
					#mise a jour de la zone d'aide
					imgnuage, background_rect = datas.load_image('images', 'fond-menu.bmp')
					Gbackground_image.blit(imgnuage, (300, 300), (300, 300, 370, 200))

					if pygame.mixer.music.get_busy :
						pygame.mixer.music.stop()

					if ( obj.id == 1 ) :
						#activite move
						pygame.mixer.music.stop()
						pysymove.ShowWindow(0)
						screen.blit(Gbackground_image, (0,0))
						LstBtn.draw(screen)	
						screen.blit(GMaSouris, GMaSouris_position)
						pygame.display.flip()
					if ( obj.id == 2) :
						#activite click
						pygame.mixer.music.stop()
						pysyclick.ShowWindow(0)
						screen.blit(Gbackground_image, (0,0))
						LstBtn.draw(screen)	
						screen.blit(GMaSouris, GMaSouris_position)
						pygame.display.flip()
					if ( obj.id == 3) :
						#activite boutons
						pygame.mixer.music.stop()
						pysybuttons.ShowWindow(0)
						screen.blit(Gbackground_image, (0,0))
						LstBtn.draw(screen)	
						screen.blit(GMaSouris, GMaSouris_position)
						pygame.display.flip()
					if ( obj.id == 4) :
						#Quitter
						pygame.mixer.music.stop()
						return 0
					break

			LstBtn.draw(screen)

			#redessin de la souris a sa position actuelle
			screen.blit(GMaSouris, GMaSouris_position)

		return 1
	return 1





#*******************************************************************************
# boucle principale
# si typfull = 0 : mode fenetre
#			 = 1 : mode plein ecran
#*******************************************************************************
def main(typfull):
	global GMaSouris
	global GMaSouris_position
	global Gbackground_image	#image de fond

	random.seed()

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

	#----------------------  Initialise son --------------------------------
	try:
		pygame.mixer.pre_init(44100, -16, 2, 2048)
		pygame.mixer.init()
		snd = 1
	except:
		snd = None

	#----------------------  Initialise screen -----------------------------
	pygame.init()

	#musique de fond
#	music = os.path.join('sounds', '04.ogg')
#	pygame.mixer.music.load(music)
#	pygame.mixer.music.play(-1)

	pygame.mouse.set_visible(0) 	#on cache la souris pour tout le jeu

	#recuperation de la valeur de la langue
	locale.setlocale(locale.LC_ALL,"")
	const.GMyLocale, myencoding = locale.getlocale()
	myrep = os.path.join(const.GRepPysycache, 'help', const.GMyLocale )
	
	if os.path.isdir(myrep):
		#le repertoire de la locale existe : rien a faire
		pass
	else :
		#on essaie sur les deux premiers caracteres
		myrep = os.path.join(const.GRepPysycache, 'help', const.GMyLocale[0:2])
		if os.path.isdir(myrep):
			#le repertoire de la (nouvelle) locale existe : rien a faire
			const.GMyLocale = const.GMyLocale[0:2]
			pass
		else :
			const.GMyLocale = 'en_EN'

	if typfull == 0:
		screen = pygame.display.set_mode((800, 600))
	else:
		screen = pygame.display.set_mode((800, 600), FULLSCREEN)
	pygame.display.set_caption('PySyCache')

	#-------------------------- image vide de fond -----------------------------
	background_image, background_rect = datas.load_image('images', 'fond1.bmp')
	screen.blit(background_image, (0,0))
	pygame.display.flip()

	#attende de 1 secondes
	pygame.time.delay(500)

	#------------------ transition vers le titre du jeu ------------------------
	background_image2, background_rect = datas.load_image('images', 'fond2.bmp')
	for i in range(300):
		screen.blit(background_image2, (0, i), (0, i, 800, 1))
		screen.blit(background_image2, (0, 600 - i), (0, 600 - i, 800, 1))
		pygame.display.flip()
		pygame.time.wait(DUREETRANSITION / 2)
	screen.blit(background_image2, (0,0))
	pygame.display.flip()
	
	#attende de 2 secondes
	pygame.time.delay(2000)
	
	#----------------------- transition vers le menu ---------------------------
	Gbackground_image, background_rect = datas.load_image('images', 'fond-menu.bmp')
	for i in range(300):
		screen.blit(Gbackground_image, (0, i), (0, i, 800, 1))
		screen.blit(Gbackground_image, (0, 600 - i), (0, 600 - i, 800, 1))
		pygame.display.flip()
		pygame.time.wait(DUREETRANSITION) 
	screen.blit(Gbackground_image, (0,0))
	pygame.display.flip()

	#-------------------- liste des boutons ----------------------
	const.GBtnMenu = 999
	global LstBtn
	LstBtn = pygame.sprite.RenderClear()
	#menu vers activite move
	LstBtn.add(BtnMenu(60, 340, 'menu-move.png', 1, 170, 170))

	#menu vers activite click
	LstBtn.add(BtnMenu(230, 140, 'menu-click.png', 2, 170, 170))

	#menu vers activite boutons
	LstBtn.add(BtnMenu(470, 80, 'menu-button.png', 3, 170, 170))

	#menu quitter
	LstBtn.add(BtnMenu(25, 535, 'menu-quitter.png', 4, 186, 60))

	#redessin de la souris a sa position initiale
	#------------------- changer la souris en main -------------------------
#	filename = os.path.join('images', 'souris.xbm')
#	maskname = os.path.join('images', 'souris-mask.xbm')
#	cursor = pygame.cursors.load_xbm(filename, maskname)
#	cursor = cursor[0], (cursor[0][0] / 2, cursor[0][1] / 2), cursor[2], cursor[3]
#	pygame.mouse.set_cursor(cursor[0], (0, 0), cursor[2], cursor[3])
	filename = dirname = os.path.join(const.GRepPysycache, 'images', 'souris.png')
	GMaSouris = pygame.image.load(filename)
	GMaSouris_position = GMaSouris.get_rect()
	GMaSouris_position.left = 400  # const.GPosDepX 
	GMaSouris_position.top = 300   # const.GPosDepY
	screen.blit(GMaSouris, GMaSouris_position)
	LstBtn.draw(screen)
	pygame.display.flip()
	pygame.mouse.set_pos((GMaSouris_position.left, GMaSouris_position.top))

	#---------------------- entree dans la boucle principale -------------------
	clock = pygame.time.Clock ()
	running = 1
	while running:
		clock.tick ( 60 )	#max 60 fps / sec

		#recherche des evt
		running = DetectEvent()
		pygame.display.flip()

	#-------------------------------- fin du jeu -------------------------------
	Gbackground_image, background_rect = datas.load_image('images', 'fond4.bmp')
	for i in range(300):
		screen.blit(Gbackground_image, (0, i), (0, i, 800, 1))
		screen.blit(Gbackground_image, (0, 600 - i), (0, 600 - i, 800, 1))
		pygame.display.flip()
		pygame.time.wait(DUREETRANSITION)
	screen.blit(Gbackground_image, (0,0))
	pygame.display.flip()

	#attende de 2 secondes
	pygame.time.delay(1000)

	#------------------ affichage des credits ------------------------
	if const.GWithCredits :
		myfont = os.path.join(const.GRepPysycache, 'fonts', 'FreeSansBold.ttf' )
		font = pygame.font.Font(myfont, 30)
		textcolor = 46, 113, 169

		#credits auteur
		fichier = os.path.join(const.GRepPysycache, 'credits.txt')
		if os.path.isfile(fichier):
			#afficher le contenu 
			f = open(fichier, 'r')
			lignes  = f.readlines()
			cptligne = 0;
			for j in lignes:
				j = j.strip()
				text = font.render(unicode(j, "utf-8"), 1, textcolor)
				screen.blit(text, (50, 30 + 40 * cptligne))	  
				cptligne = cptligne + 1
			pygame.display.flip()
			f.close()

		pygame.time.wait(3000) 

		#credit images for themes
		ReadCreditOfDirectory('themes-buttons')
		ReadCreditOfDirectory('themes-click')
		ReadCreditOfDirectory('themes-move')
	






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


#valeur par defaut
const.GWithFullScreen = 1
const.GWithSound = 1
const.GWithCredits = 1
const.GWithHelp = 1

# analyse des parametres passes en arguement
for opt in sys.argv:
	if opt == '-nf':
		const.GWithFullScreen = 0
	if opt == '-ns':
		const.GWithSound = 0
	if opt == '-nc':
		const.GWithCredits = 0
	if opt == '-nh':
		const.GWithHelp = 0

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



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