#!/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 random, os
import pygame
from pygame.locals import *
import glob


import const
import datas
from pysyclasses import *
import pysyscores


CARREAUBIG = 0
CARREAUNORMAL = 1
CARREAUSMALL = 2



#*******************************************************************************
#    
#*******************************************************************************
class Carreau:
	"""Carreau : partie du cache - Est affiche lorsque la souris passe dessus """
	numligne = 0
	numcol = 0
	etat = const.CACHE



#*******************************************************************************
#    
#*******************************************************************************
class ApplicationMove(ApplicationPysy):
	def __init__(self):
		ApplicationPysy.__init__(self)

		self.GLstImage = []									#liste des images a decouvrir (dans le repertoire de theme)
		self.GLstImgCache = []								#liste des images qui cachent (dans le repertoire de theme)
		self.GLstSndCache = []								#liste des sons des caches (dans le repertoire de theme)
		self.GCacheImage = pygame.Surface((720, 540))		#cache de l'image 
		self.GImageATrouver = pygame.Surface((720, 540))	#image a trouver
		self.GIdxCache = 0									#Indice du cache dans sa liste
		self.OldCarrePositionLePositionTop = 0


	#***************************************************************************
	#
	#***************************************************************************
	def InitializeApp(self, DirThemes, ActName):
		ApplicationPysy.InitializeApp(self, DirThemes, ActName)

		if const.GWithSound == 1:
			if const.GSoundError == 0:
				self.Channel0 = pygame.mixer.Channel(0)
				self.Channel1 = pygame.mixer.Channel(1)
				music = os.path.join(const.GRepPysycache, 'sounds', 'pop.wav').encode(const.GConsoleLocale)
				self.Sound0 = pygame.mixer.Sound(music)
				music = os.path.join(const.GRepPysycache, 'sounds', 'fantom.wav').encode(const.GConsoleLocale)
				self.Sound1 = pygame.mixer.Sound(music)

		self.TimeWaitAfterWin = 2000


	#***************************************************************************
	# Retour 0 : on a pas gagne
	#        1 : on a gagne  
	#***************************************************************************
	def OnAGagne(self, gagne):
		if (const.GNbCarreau == 0):
			gagne = 1
		else:
			gagne = 0
		return gagne


	#***************************************************************************
	#
	#***************************************************************************
	def DoPlayerGagne(self):
		if const.GWithSound == 1:
			#on joue la musique de l'image
			(shortname, extension) = os.path.splitext(self.LstFicConfig[self.IdxFileDfg]) 
			music = os.path.join(const.GRepPysycache, "themes-move", self.LstThemesOfActivity[self.IdxThemes], shortname + '.ogg')
			if os.path.isfile(music) == True:
				datas.Load_sound(os.path.join("themes-move", self.LstThemesOfActivity[self.IdxThemes]), shortname + '.ogg')
			else:
				datas.Load_sound(os.path.join("themes-move", self.LstThemesOfActivity[self.IdxThemes]), shortname + '.wav')
			pygame.time.wait(500)


	#***************************************************************************
	#
	#***************************************************************************
	def DoInitLevel(self):
		"""Get the size of a tile by level """

		if const.GLevel == 0:
			const.GTailleCarreau = CARREAUBIG
			const.GTailleLarg = 120		#720 / 6
			const.GTailleHaut = 90		#540 / 6
		elif const.GLevel == 1 :
			const.GTailleCarreau = CARREAUNORMAL
			const.GTailleLarg = 72		#720 / 10
			const.GTailleHaut = 54		#540 / 10
		else:
			const.GTailleCarreau = CARREAUSMALL
			const.GTailleLarg = 48		#720 / 15
			const.GTailleHaut = 36		#540 / 15



	#***************************************************************************
	#
	#***************************************************************************
	def EndOfActivity(self):
		pygame.time.set_timer (const.EVTFANTOME, 0 ) 


	#***************************************************************************
	#
	#***************************************************************************
	def DoTheFantomEvent(self):
		ApplicationPysy.DoTheFantomEvent(self)

		if const.GModeJeu == const.MODEFANTOM:
			#on est en mode fantome, on va voir si on fait 
			#reapparaitre des carres
			lefthaz = random.randint(0, 720 / const.GTailleLarg - 1)
			tophaz = random.randint(0, 540 / const.GTailleHaut - 1)
			cpt = 0
			for car in const.GTabCarreau:
				if (car.numligne == lefthaz) & (car.numcol == tophaz):
					if car.etat == const.CACHE:
						#toujours cache
						pass
					else:
						#on affiche a nouveau le cache
						nouveauleft = lefthaz * const.GTailleLarg 
						nouveautop = tophaz * const.GTailleHaut 

						#on affiche le carre de nouvelle image
						tr2 = pygame.Rect([nouveauleft, nouveautop, const.GTailleLarg, const.GTailleHaut] )
						self.Background.blit(self.GCacheImage, [nouveauleft + const.MARGELEFT, nouveautop + const.MARGETOP], tr2 )
						const.GNbCarreau += 1
						car.etat = const.CACHE

						tr2 = pygame.Rect([nouveauleft + const.MARGELEFT, nouveautop + const.MARGETOP, const.GTailleLarg, const.GTailleHaut] )
						screen = pygame.display.get_surface() 
						screen.blit(self.Background, (nouveauleft + const.MARGELEFT, nouveautop + const.MARGETOP), tr2)
						pygame.display.update()

						#on joue la musique
						if const.GWithSound == 1:
							if const.GSoundError == 0:
								self.Channel1.play(self.Sound1)
#						datas.Load_sound("sounds", 'fantom.wav')


	#***************************************************************************
	#
	#***************************************************************************
	def InitActivity(self, WithHasard):
		ApplicationPysy.InitActivity(self, WithHasard)

		const.GTabCarreau[:] = []   	#vider
										#tableau avec toutes les infos sur les carreaux

		const.GTypeSouris = const.EVENT_NOVENT
		OldCarrePositionLeft = 0
		OldCarrePositionTop = 0

		#initialisation des carres : la taille d'une photo est de 720 x 540
		nblarg = 720 / const.GTailleLarg
		nbhaut = 540 / const.GTailleHaut
		const.GNbCarreau = nblarg * nbhaut

		for i in range(nblarg):
			for j in range(nbhaut):
				car = Carreau()
				car.numligne = i
				car.numcol = j
				car.etat = const.CACHE
				const.GTabCarreau.append(car)

		directory = self.LstThemesOfActivity[self.IdxThemes]

		#on choisi une image (pas au hasard car est fait lors d'une etape avant)
		if len(self.GLstImage) == 1:
			imgdessous = self.GLstImage[0]
		else :
			idx = len(self.GLstImage)
			imgdessous = self.GLstImage[random.randint(0, idx - 1)]
		datas.DebugMessage("")
		datas.DebugMessage("picture to uncover is : %s " % imgdessous)

		#on choisi un cache (au hasard) parmi ceux associes a l'image...
		strtmp = self.GLstImgCache
		if WithHasard == True:
			if len(self.GLstImgCache) == 1:
				self.GIdxCache = 0
			else :
				self.GIdxCache = random.randint(0, len(self.GLstImgCache) - 1)
		imgcache =  strtmp[self.GIdxCache]

		#chargement du dessin servant de cache
		filename = os.path.join(directory, 'cache', imgcache)
		datas.DebugMessage("")
		datas.DebugMessage("picture used as cache : %s " % filename)
		self.GCacheImage, background_rect = datas.Load_image("", filename, None, True)

		#on copie ce cache sur l'image de fond
		self.Background.blit(self.GCacheImage, (0 + const.MARGELEFT, 0 + const.MARGETOP))
		#on copie cette image sur l'ecran
		screen = pygame.display.get_surface()  
		screen.blit(self.Background, (0, 0 ))

		#si le cache est associe a un son, on le joue
		if const.GWithSound == 1:
			sndcache = self.GLstSndCache[self.GIdxCache]
			(filepath, filename) = os.path.split(sndcache)
			datas.Load_sound(filepath, filename)
			pygame.time.wait(200)

		#chargement du dessin a trouver
		filename = os.path.join(directory, imgdessous)
		self.GImageATrouver, background_rect = datas.Load_image("", filename, None, True)


	#***************************************************************************
	#
	#***************************************************************************
	def MotionBeforeMouse(self, event0, event1, str):
		ApplicationPysy.MotionBeforeMouse(self, event0, event1, str)


	#***************************************************************************
	#
	#***************************************************************************
	def MotionAfterMouse(self, event0, event1, str):
		ApplicationPysy.MotionAfterMouse(self, event0, event1, str)

		#------------- on va afficher ce que cachait la souris -----------------
		caseleft = int( (const.GMaSourisCurrentPositionX + const.DEMISOURIS - const.MARGELEFT ) / const.GTailleLarg )
		casetop = int( (const.GMaSourisCurrentPositionY + const.DEMISOURIS - const.MARGETOP) / const.GTailleHaut )

		#recherche si deja coche
		for car in const.GTabCarreau:
			if (car.numligne == caseleft) & (car.numcol == casetop):
				if car.etat == const.CACHE:
					car.etat = const.VISIBLE

					nouveauleft = caseleft * const.GTailleLarg 
					nouveautop = casetop * const.GTailleHaut

					#on affiche le carre de nouvelle image
					tr2 = pygame.Rect([nouveauleft, nouveautop, const.GTailleLarg, const.GTailleHaut] )
					self.Background.blit(self.GImageATrouver, [nouveauleft + const.MARGELEFT, nouveautop + const.MARGETOP], tr2 )
					screen = pygame.display.get_surface()
					screen.blit(self.GImageATrouver, [nouveauleft + const.MARGELEFT, nouveautop + const.MARGETOP], tr2 )
					pygame.display.update(tr2)

					const.GNbCarreau = const.GNbCarreau - 1

					#on joue la musique
#					datas.Load_sound("sounds", 'pop.ogg')
					if const.GWithSound == 1:
						if const.GSoundError == 0:
							self.Channel0.play(self.Sound0)

				break


	#***************************************************************************
	#    
	#***************************************************************************
	def ReadDfgFile(self):
		ApplicationPysy.ReadDfgFile(self)

		#vider
		self.GLstImage[:] = []
		self.GLstImgCache[:] = []	#va servir a recuperer la liste des caches
		self.GLstSndCache[:] = []	#va servir a recuperer les sons associes aux caches
		strimg = ''

		#recuperation du nom (et du chemin) du fichier de configuration
		nom = self.LstFicConfig[self.IdxFileDfg]

		#--- recuperation du nom (hors chemin) du fichier de definition ----
		(filepath, filename) = os.path.split(nom)

		#------------- recherche de toutes les images a decouvrir -------------
		#qui ont par definition le meme nom que le fichie de definition + '.jpeg' ou '.png' ou '.jpg'
		(shortname, extension) = os.path.splitext(filename) 
		strimg = shortname + '.jpeg'
		nomnormal = os.path.join(filepath, strimg)
		if ( os.path.isfile(nomnormal) ):
			self.GLstImage.append(nomnormal)
		else:
			strimg = shortname + '.jpg'
			nomnormal = os.path.join(filepath, strimg)
			if ( os.path.isfile(nomnormal) ):
				self.GLstImage.append(nomnormal)
			else :
				strimg = shortname + '.png'
				nomnormal = os.path.join(filepath, strimg)
				if (os.path.isfile(nomnormal) ):
					self.GLstImage.append(nomnormal)

		#lecture du fichier de definition
		#-------- recherche de toutes les images servant de cache ----------
		#----------------- en lisant le fichier de definition --------------
		datas.DebugMessage("")
		datas.DebugMessage("Reading the .dfg file...")

		f = open(nom, 'r')
		lignes  = f.readlines()
		for lig in lignes:
			lig = lig.strip()
			lig = lig.split(',')

			if len(lig) == 0:
				continue

			#fichier de cache
			nomcache = os.path.join(filepath, 'cache', lig[0])
			if os.path.isfile(nomcache):
				datas.DebugMessage("... available cache : %s " % nomcache)
				self.GLstImgCache.append(nomcache)

				#fichier de son
				if len(lig) > 1:
					nomcache = os.path.join(filepath, 'cache', lig[1])
				else:
					nomcache = ""
				self.GLstSndCache.append(nomcache)
			else:
				datas.DebugMessage("error in definition file : cache file %s doesn't exist" %nomcache)

		f.close()
