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

import pysyscores


VIEWNEVER = 1
VIEWALREADY = 0

PHOTOLOIN = 0
PHOTOPRES = 1



#*******************************************************************************
#                                       Classes                                #
#*******************************************************************************


class Photo:
	left = 0
	id = 0
	top = 0
	ray = 0
	view = VIEWNEVER	#0 : oui deja vue
						#1 : non pas encore vue
#	mode = 0 # PHOTOLOIN	#0 : je suis loin d'une photo	
#						#1 : je suis sur une photo, je peux cliquer
	miniature = ""



#*******************************************************************************
#    
#*******************************************************************************
class ApplicationClick(ApplicationPysy):
	def __init__(self):
		ApplicationPysy.__init__(self)
		self.GImgBackground = ""
		self.EtatPhoto = PHOTOLOIN


	#***************************************************************************
	#
	#***************************************************************************
	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', 'photo-click.wav').encode(const.GConsoleLocale)
				self.Sound0 = pygame.mixer.Sound(music)
				music = os.path.join(const.GRepPysycache, 'sounds', 'photo-beep0.wav').encode(const.GConsoleLocale)
				self.Sound1 = pygame.mixer.Sound(music)



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

		return gagne


	#***************************************************************************
	#
	#***************************************************************************
	def RAZMiniatures(self):
		screen = pygame.display.get_surface()  

		cpt = 0
		for pho in const.GTabPhotos:
			imgtmp, rectmp = datas.Load_image("", pho.miniature + '-off.png', None, True)
			self.Background.blit(imgtmp, (20 + 105 * pho.id, 547 ))
			screen.blit(imgtmp, (20 + 105 * pho.id, 547))
			cpt += 1


	#***************************************************************************
	#
	#***************************************************************************
	def GetIdOfPhotoToFound(self):
		""" """

		if const.GModeJeu == const.MODENORMAL:
			const.GItemToFound = 99
		else:
			const.GItemToFound = random.randint(0, len(const.GTabPhotos) - 1)
			ok = 0
			while ok == 0:
				if const.GTabPhotos[const.GItemToFound].view == VIEWNEVER:
					#photo pas encore vue... on met son pictogramme a jaune
					for img in const.GTabPhotos :
						if img.id == const.GItemToFound :
							imgtmp, rectmp = datas.Load_image("", img.miniature + '-selected.png', None, True)
							self.Background.blit(imgtmp, (20 + 105 * img.id, 547))
							screen = pygame.display.get_surface() 
							screen.blit(imgtmp, (20 + 105 * img.id, 547))
							break
					ok = 1
				else:
					#photo deja vue... on recommence
					const.GItemToFound = random.randint(0, len(const.GTabPhotos) - 1)

			datas.DebugMessage("Picture to found %i " % const.GItemToFound)

			pygame.display.update()


	#***************************************************************************
	#
	#***************************************************************************
	def SetMousePicture(self):
		return 'souris-click1.png'

#		const.GLstSouris.add(MouseOfActivity(const.GPosDepX, const.GPosDepY, 'souris-' + self.ActivityName + '.png') )


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

		#recherche de la photo concernee
		inarea = 0
		for car in const.GTabPhotos:
			x = car.left - (event0 + const.DEMISOURIS)
			y = car.top - (event1 + const.DEMISOURIS)

			if (x * x + y * y < const.GTailleZoom * const.GTailleZoom):
				screen = pygame.display.get_surface()  
				#on est dans la zone proche de la photo
				#on joue la musique
				const.GTypeSouris = const.EVENT_JEU2

				#photos pas encore vue... elle le devient
				#on affiche les infos
				okmaj = 0
				if const.GModeJeu == const.MODEFANTOM:
					#mode fantome : on affiche que si c'est la photo avec le bon id
					if const.GItemToFound == car.id:
						okmaj = 1
					else:
						okmaj = 0
				else:
					okmaj = 1

				if okmaj == 1:
					#on decompte la photo des photos a trouver
					if car.view == VIEWNEVER:
						const.GNbPhotos += 1
						car.view = VIEWALREADY

					#mise a jour de la miniature representant la photo prise
					for img in const.GTabPhotos :
						if img.id == car.id :
							imgtmp, rectmp = datas.Load_image("", img.miniature + '-on.png', None, True)
							self.Background.blit(imgtmp, (20 + 105 * img.id, 547))
							screen.blit(imgtmp, (20 + 105 * img.id, 547))
							break

#				datas.Load_sound("sounds", "photo-click.ogg")
				if const.GWithSound == 1:
					if const.GSoundError == 0:
						self.Channel0.play(self.Sound0)

				#on affiche la photo
				imgtmp, rectmp = datas.Load_image("",  car.chemin, None, True)
				(larg, haut) = imgtmp.get_size()
				x = (720 - larg) / 2 + const.MARGELEFT
				y = (540 - haut) / 2 + const.MARGETOP
				screen.blit(imgtmp, [x, y])
				pygame.display.update()

				#on patiente deux secondes
				tpsdepartattente = pygame.time.get_ticks()
				self.ShowOnlyChrono = 1
				while ( float(pygame.time.get_ticks() - tpsdepartattente) < 2000 ):
					for event in pygame.event.get(const.EVTCHRONO):
						if event.type == const.EVTCHRONO:
							self.DoTheChronoEvent()
				self.ShowOnlyChrono = 0

				#on efface tout
				screen.blit(self.Background, (x, y), (x, y, larg, haut))

				#on recherche une nouvelle photo
				if okmaj == 1:
					if const.GNbPhotos  < 6 :
						self.GetIdOfPhotoToFound()

				const.GLstSouris.draw(screen)
				pygame.display.update()
				const.GTypeSouris = const.EVENT_JEU0
				self.EtatPhoto = PHOTOPRES


	#***************************************************************************
	#
	#***************************************************************************
	def DoInitLevel(self):
		""" """
		if const.GLevel == 0:
			const.GTailleZoom = 50
		elif const.GLevel == 1:
			const.GTailleZoom = 35
		else:
			const.GTailleZoom = 20

		datas.DebugMessage("Rayon= %i " % const.GTailleZoom)



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

		imgtmp, rectmp = datas.Load_image("", self.GImgBackground, True)
		self.Background.blit(imgtmp, (const.MARGELEFT, const.MARGETOP))

		screen = pygame.display.get_surface()
		if const.GDebug == 1:
			#on affiche une cible a la position d'une photo a trouver
			imgcible, rectcible = datas.Load_image("images", "cible.png" )
			(imglar, imght) = imgcible.get_size()
			for car in const.GTabPhotos:
				self.Background.blit(imgcible, (car.left - int(imglar/2), car.top - int(imght/2)))


		const.GNbPhotos = 0
		const.GItemToFound = 99
		
		#recherche du rayon en fonction du niveau
		self.DoInitLevel()

		self.RAZMiniatures()

		self.GetIdOfPhotoToFound()


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

		#recherche de la photo
		inarea = 0
		for car in const.GTabPhotos:
			x = car.left - (const.GMaSourisCurrentPositionX + const.DEMISOURIS)
			y = car.top - (const.GMaSourisCurrentPositionY + const.DEMISOURIS)

			if (x * x + y * y < const.GTailleZoom * const.GTailleZoom):
				#on est dans la zone proche de la photo
				#on affiche l'appareil photo en rouge pour indiquer 
				inarea = 1
				break

		if inarea == 1:
			#on est bien proche d'une photo
			#on peut afficher l'appareil photo en rouge
			if const.GTypeSouris == const.EVENT_JEU0:
				if self.EtatPhoto == PHOTOLOIN:
					#on est actuellement en appareil photo normal et on passe en mode couleur
#					datas.Load_sound("sounds", "photo-beep0.ogg")
					if const.GWithSound == 1:
						if const.GSoundError == 0:
							self.Channel1.play(self.Sound1)

				const.GLstSouris.empty()
				const.GLstSouris.add(MouseOfActivity(const.GMaSourisCurrentPositionX, const.GMaSourisCurrentPositionY, 'souris-click0.png') )
				const.GTypeSouris = const.EVENT_JEU1
				self.EtatPhoto = PHOTOPRES
			else:
				#on est deja en appareil photo en couleur : on ne fait rien
				pass
		else:
			#on est loin d'une photo : 
			#il faut remettre l'appareil photo en normal
			if const.GTypeSouris == const.EVENT_JEU0:
				#on est actuellement en appareil photo normal
				#on ne change pas
				pass
			else:
				#on est en appareil photo en couleur : on passe a normal
				const.GLstSouris.empty()
				const.GLstSouris.add(MouseOfActivity(const.GMaSourisCurrentPositionX, const.GMaSourisCurrentPositionY, 'souris-click1.png') )
				const.GTypeSouris = const.EVENT_JEU0
				self.EtatPhoto = PHOTOLOIN



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

		""" Charge les photos a partir d'un fichier de configuration contenus dans le repertoire"""
		screen = pygame.display.get_surface()

		#effacer l'existant
		const.GTabPhotos[:] = []

		LstFound = []

		#------------------ on va lire le fichier de configuration -----------------
		configname = self.LstFicConfig[self.IdxFileDfg]

		(dirpath, dirname) = os.path.split(configname)

		cpt = 0
		f = open(configname,'rb') 
		lignes = f.readlines()
		for lig in lignes:
			lig = lig.strip()
			if len(lig) == 0:
				continue

			if cpt == 0:
				self.GImgBackground = os.path.join(dirpath, lig)
			else:
				#recuperation des photos pour l'activite
				pho = Photo()
				lig = lig.split('|')
				(shortname, extension) = os.path.splitext(lig[0]) 

				pho.chemin = os.path.join(dirpath, lig[0])
				pho.miniature = os.path.join(dirpath, shortname)			#nom (sans extension de la miniature)
				pho.id = cpt - 1
				pho.left = int(lig[1]) + const.MARGELEFT
				pho.top = int(lig[2]) + const.MARGETOP
				pho.ray = int(lig[3])
				pho.view = VIEWNEVER				#pas encore vue
				const.GTabPhotos.append(pho)

				datas.DebugMessage("...photo named " + shortname + " position on background : left=" + str(pho.left) + " top="  + str(pho.top))

			cpt += 1
		f.close()

		#MAJ du nombre de photos vues
		const.GNbPhotos = 0
