import pygame
import sys
import time
import subprocess
import os
from pygame.locals import *
from pygame import *
from pygame import movie
#from pygame.movie import *
from DefFrontEndEmuMapFile import *
from DefFrontEndEmuFile import *
from ConfAllPath import *
from DefFrontEndGameMapFile import DefFrontEndGameMap
from DefLaunchSomethingFile import DefLaunchSomething
from DefDownladPerGame import DownloadGraphical
from DefCheckEnvFile import DefCheckEnv
from KeyMapKeyBoard import *
from time import gmtime, strftime






def DefFrontEndGame(EmuChoose,Resolution,emu,li,CptGame,MAX_EMU,MAX,CptEmu,GamePerEmu,MaxForThisEmu,Orientation,JOY_TEST):
	
	Sys=DefCheckEnv()[0]
	pygame.key.set_repeat(400, 70)
#	Orientation='X'
	ParentOfPyr,ConfRomFile,AllMedia,ConfigKeyboardFile=DefConfPathHome()



	font_path,font_size,max_carac,WHERE_TEXTE,WHERE_TEXTE_X,WHERE_TEXTE_Y,SIZE_TEXTE_W,SIZE_TEXTE_H,SIZE_TEXTE,WHERE_WHEEL,WHERE_SYS,SIZE_WHEEL_CONVERT,WHERE_SNAP,SIZE_SNAP_CONVERT,SIZE_SYS_CONVERT,UNIT_L,UNIT_H=DefFrontEndGameMap(Resolution,Orientation)
	font = pygame.font.Font(font_path, font_size)
	ParentOfPyr,BinOfPyr,Wheel,Snap,Sound,Roms,Docs,ImgY,ImgX,Img,BlackImg,IMG_EMU=DefConfPathGame(Orientation)
	BeepFileGame=ParentOfPyr + "/MEDIA/SOUND/blip.wav"
	MyBip=pygame.mixer.Sound(BeepFileGame)
	pygame.init()
	PyrScreen =   pygame.display.set_mode(Resolution,FULLSCREEN)
	if Orientation=='Y':

		### TODO
		if (os.path.isfile(ImgY + EmuChoose + ".png")):
			Background=Img + "/black.png"
		else:
			Background=Img + "/black.png"
		### ODOT
	else:
		if (os.path.isfile(ImgX + EmuChoose + ".png")):
			Background=ImgX + EmuChoose + ".png"
		else:
			Background=Img + "/menu_X.png"
	fond = pygame.transform.scale(pygame.image.load(Background).convert(),Resolution)
	PyrScreen.blit(fond, (0,0))
	
	
	PyrScreen.blit(pygame.transform.scale(pygame.image.load(BlackImg).convert(),(SIZE_SNAP_CONVERT)),WHERE_SNAP)
	PyrScreen.blit(pygame.transform.scale(pygame.image.load(BlackImg).convert(),(SIZE_SYS_CONVERT)),WHERE_SYS)
	PyrScreen.blit(pygame.transform.scale(pygame.image.load(BlackImg).convert(),(SIZE_WHEEL_CONVERT)),WHERE_WHEEL)


	GameSnapPath=AllMedia+EmuChoose+ "/SNAP/" + GamePerEmu[CptGame][0]+".png"
	GameWheelPath=AllMedia+EmuChoose+ "/WHEEL/" + GamePerEmu[CptGame][0]+".png"
	GameSysPath=AllMedia + "/IMG/EMU/LOGO/" + EmuChoose +".png"
	GameDocPath=AllMedia+EmuChoose+ "/DOCS/" + GamePerEmu[CptGame][0]+".txt"
	GameVideoPath=AllMedia+EmuChoose+ "/VIDEO/" + GamePerEmu[CptGame][0]+".mpg"




	if (os.path.isfile(GameSysPath)):
		GameSys=pygame.transform.scale(pygame.image.load(GameSysPath).convert_alpha(),SIZE_SYS_CONVERT)
	else:
		GameSysPath=AllMedia+"/no_sys.png"
		GameSys=pygame.transform.scale(pygame.image.load(GameSysPath).convert_alpha(),SIZE_SYS_CONVERT)
		
	


	if (os.path.isfile(GameSnapPath)):
		GameSnap=pygame.transform.scale(pygame.image.load(GameSnapPath).convert_alpha(),SIZE_SNAP_CONVERT)
	else:
		GameSnapPath=AllMedia+"/no_snap.png"
		GameSnap=pygame.transform.scale(pygame.image.load(GameSnapPath).convert_alpha(),SIZE_SNAP_CONVERT)
		
		
	if (os.path.isfile(GameWheelPath)):
		GameWheel=pygame.transform.scale(pygame.image.load(GameWheelPath).convert_alpha(),SIZE_WHEEL_CONVERT)
	else:
		GameWheelPath=AllMedia+"/no_wheel.png"
		GameWheel=pygame.transform.scale(pygame.image.load(GameWheelPath).convert_alpha(),SIZE_WHEEL_CONVERT)
	FILE_INFO=AllMedia+EmuChoose+ "/DOCS/" + GamePerEmu[CptGame][0]+".txt"
	if os.path.isfile(FILE_INFO):
		FILE_DOC = open(FILE_INFO,"r")
		text1 = FILE_DOC.read()
		LPLUS=0
		LPLUS=LPLUS + (font_size+3)
		WHERE_TEXTE=(WHERE_TEXTE_X,WHERE_TEXTE_Y)
		PyrScreen.blit(pygame.transform.scale(pygame.image.load(BlackImg).convert(),(SIZE_TEXTE)),(WHERE_TEXTE))
		PyrScreen.blit(pygame.transform.scale(pygame.image.load(BlackImg).convert(),(SIZE_TEXTE)),WHERE_TEXTE)
		for ligne in text1.splitlines():
			ligne=ligne[0:max_carac]
			x,y = PyrScreen.blit(font.render(ligne,10,pygame.Color("red")),(WHERE_TEXTE_X,WHERE_TEXTE_Y+LPLUS)).bottomleft
			LPLUS=LPLUS + (font_size+1)
			if ((WHERE_TEXTE_Y + LPLUS) > (SIZE_TEXTE_H*3 +(UNIT_H*2))):
				break
		FILE_DOC.close()
	else:
		text1 = "No DATA File : " #+ GamePerEmu[CptGame][MAX_EMU][0]
		text2 = font.render(text1, True, pygame.Color("red"))
		PyrScreen.blit(pygame.transform.scale(pygame.image.load(BlackImg).convert(),(SIZE_TEXTE_W,SIZE_TEXTE_H)),((WHERE_TEXTE_X,WHERE_TEXTE_Y)))

		PyrScreen.blit(pygame.transform.scale(pygame.image.load(BlackImg).convert(),(SIZE_TEXTE)),WHERE_TEXTE)
		PyrScreen.blit(text2,(WHERE_TEXTE_X,WHERE_TEXTE_Y+50)).bottomleft




	PyrScreen.blit(GameSnap,WHERE_SNAP)
	PyrScreen.blit(GameSys,WHERE_SYS)
	PyrScreen.blit(GameWheel,WHERE_WHEEL)
	pygame.display.flip()


	KeepInGame = 1
	FrontEndGame = 1
	ExitStatus = 0
	T1=0
	while KeepInGame == 1:
			
		for event in pygame.event.get():
			#T1=(time.time())
			T1=strftime("%H%M%S", gmtime())

			PyrScreen.blit(pygame.transform.scale(pygame.image.load(BlackImg).convert(),(SIZE_TEXTE)),WHERE_TEXTE)
			if JOY_TEST == 1 :
				if event.type == JOYAXISMOTION:
					if event.axis == 0 and event.value > 0:
						CptGame = CptGame + 1
					if event.axis == 0 and event.value < 0:
						CptGame = CptGame - 1
					if event.axis == 1 and event.value < 0:
						ROM_L1 = GamePerEmu[CptGame][0][0]
						ROM_L2 = ROM_L1
						while (ROM_L1 == ROM_L2):
							CptGame = CptGame + 1
							if CptGame >= MaxForThisEmu:
								CptGame=0
								break
							ROM_L1 = GamePerEmu[CptGame][0][0]
					if event.axis == 1 and event.value > 0:
						ROM_L1 = GamePerEmu[CptGame][0][0]
						ROM_L2 = ROM_L1
						while (ROM_L1 == ROM_L2):
							CptGame = CptGame - 1
							if CptGame <= -MaxForThisEmu:
								CptGame=0
								break
							ROM_L1 = GamePerEmu[CptGame][0][0]
				if event.type == JOYBUTTONDOWN:
					if event.button == BTN_J1_2:
						FrontEndGame = 0
						ExitStatus = 0
						KeepInGame = 0
						FrontEndEmu = 1
						CptEmu = 0
					if event.button ==  BTN_J1_1:
						FrontEndGame = 0
						FrontEndGame = 1
						ExitStatus = 0
						KeepInGame= 1
						FrontEndEmu = 0
						GameChoose = GamePerEmu[CptGame][0]
						DefLaunchSomething(EmuChoose,GameChoose,AllMedia,font,Resolution,BlackImg,WHERE_TEXTE,SIZE_TEXTE,Background,Orientation)
				pygame.mixer.Sound(BeepFileGame).play()

			if JOY_TEST == 0 :
				if event.type == KEYDOWN:
					if event.key == LEFT_J1:
#					if event.key == K_LEFT:
						CptGame = CptGame - 1
#					if event.key == K_RIGHT:
					if event.key == RIGHT_J1:
						CptGame = CptGame + 1
#					if event.key == K_UP:
					if event.key == UP_J1:
						ROM_L1 = GamePerEmu[CptGame][0][0]
						ROM_L2 = ROM_L1
						while (ROM_L1 == ROM_L2):
							CptGame = CptGame + 1
							if CptGame >= MaxForThisEmu:
								CptGame=0
								break
							ROM_L1 = GamePerEmu[CptGame][0][0]
					if event.key == DOWN_J1:
#					if event.key == K_DOWN:
						ROM_L1 = GamePerEmu[CptGame][0][0]
						ROM_L2 = ROM_L1
						while (ROM_L1 == ROM_L2):
							CptGame = CptGame - 1
							if CptGame <= -MaxForThisEmu:
								CptGame=0
								break
							ROM_L1 = GamePerEmu[CptGame][0][0]
					#  LAUNCH GAME	
					if event.key == BTN_J1_1:
#					if event.key == K_d:
						FrontEndGame = 1
						ExitStatus = 0
						KeepInGame= 1
						FrontEndEmu = 0
						GameChoose = GamePerEmu[CptGame][0]
						DefLaunchSomething(EmuChoose,GameChoose,AllMedia,font,Resolution,BlackImg,WHERE_TEXTE,SIZE_TEXTE,Background,Orientation)


	###################################################
					# DOWNLAOD MEDIA
#					if event.key == K_f:
					if event.key == BTN_J1_3:
						T1=0
						T2=0

						DownloadGraphical(EmuChoose, GamePerEmu[CptGame][0])

						PyrScreen.blit(fond, (0,0))

						T1=0
						T2=0
	###################################################
					# ESCAPE (keyboard only)
					if event.key == K_ESCAPE:
						FrontEndGame = 0
						ExitStatus = 1 
						KeepInGame=0
						FrontEndEmu = 0
					# Back to Emu Selector
					if event.key == BTN_J1_2:
#					if event.key == K_e:
						FrontEndGame = 0
						ExitStatus = 0
						KeepInGame = 0
						FrontEndEmu = 1	
						CptEmu = 0			







			
				pygame.mixer.Sound(BeepFileGame).play()


			if 	CptGame >= MaxForThisEmu:
				CptGame = -MaxForThisEmu 

			if 	CptGame < -MaxForThisEmu:
				CptGame = MaxForThisEmu -1
			if 	MaxForThisEmu == 1:
				CptGame = 0 
			GameSnapPath=AllMedia+EmuChoose+ "/SNAP/" + GamePerEmu[CptGame][0]+".png"
			if (os.path.isfile(GameSnapPath)):
				GameSnap=pygame.transform.scale(pygame.image.load(GameSnapPath).convert_alpha(),SIZE_SNAP_CONVERT)
			else:
				GameSnapPath=AllMedia+"/no_snap.png"
			GameWheelPath=AllMedia+EmuChoose+ "/WHEEL/" + GamePerEmu[CptGame][0]+".png"
			if (os.path.isfile(GameWheelPath)):
				GameWheel=pygame.transform.scale(pygame.image.load(GameWheelPath).convert_alpha(),SIZE_WHEEL_CONVERT)
			else:
				GameWheelPath=AllMedia+"/no_wheel.png"
				GameWheel=pygame.transform.scale(pygame.image.load(GameWheelPath).convert_alpha(),SIZE_WHEEL_CONVERT)
		
		
				GameSnap=pygame.transform.scale(pygame.image.load(GameSnapPath).convert_alpha(),SIZE_SNAP_CONVERT)
			
			FILE_INFO=AllMedia+EmuChoose+ "/DOCS/" + GamePerEmu[CptGame][0]+".txt"
			if os.path.isfile(FILE_INFO):
				FILE_DOC = open(FILE_INFO,"r")
				text1 = FILE_DOC.read()
				LPLUS=0
				LPLUS=LPLUS + (font_size+3)
				WHERE_TEXTE=(WHERE_TEXTE_X,WHERE_TEXTE_Y)
				PyrScreen.blit(pygame.transform.scale(pygame.image.load(BlackImg).convert(),(SIZE_TEXTE)),(WHERE_TEXTE))
				PyrScreen.blit(pygame.transform.scale(pygame.image.load(BlackImg).convert(),(SIZE_TEXTE)),WHERE_TEXTE)
				for ligne in text1.splitlines():
					ligne=ligne[0:max_carac]
					x,y = PyrScreen.blit(font.render(ligne,1,pygame.Color("red")),(WHERE_TEXTE_X,WHERE_TEXTE_Y+LPLUS)).bottomleft
					LPLUS=LPLUS + (font_size+1)
					if ((WHERE_TEXTE_Y + LPLUS) > (SIZE_TEXTE_H*3 +(UNIT_H*2))):
						break

				FILE_DOC.close()
			else:
				text1 = "No DATA File : " + GamePerEmu[CptGame][0] 
				text2 = font.render(text1, True, pygame.Color("red"))
				PyrScreen.blit(pygame.transform.scale(pygame.image.load(BlackImg).convert(),(SIZE_TEXTE_W,SIZE_TEXTE_H)),((WHERE_TEXTE_X,WHERE_TEXTE_Y)))

				PyrScreen.blit(pygame.transform.scale(pygame.image.load(BlackImg).convert(),(SIZE_TEXTE)),WHERE_TEXTE)
				PyrScreen.blit(text2,(WHERE_TEXTE_X,WHERE_TEXTE_Y+50)).bottomleft

			
					
			PyrScreen.blit(pygame.transform.scale(pygame.image.load(BlackImg).convert(),(SIZE_SNAP_CONVERT)),WHERE_SNAP)
			PyrScreen.blit(pygame.transform.scale(pygame.image.load(BlackImg).convert(),(SIZE_SYS_CONVERT)),WHERE_SYS)
			PyrScreen.blit(pygame.transform.scale(pygame.image.load(BlackImg).convert(),(SIZE_WHEEL_CONVERT)),WHERE_WHEEL)
					
			
			PyrScreen.blit(GameSnap,WHERE_SNAP)
			PyrScreen.blit(GameSys,WHERE_SYS)
			PyrScreen.blit(GameWheel,WHERE_WHEEL)
		
		if T1 == 0:
			T1=strftime("%H%M%S", gmtime())
		TDiff=int(strftime("%H%M%S", gmtime())) - int(T1)
		GameVideoPath=AllMedia+EmuChoose+ "/VIDEO/" + GamePerEmu[CptGame][0]+".mpg"


		if os.path.isfile(GameVideoPath):
			if TDiff > 2 and Sys != "Darwin":

				FPS = 60

				pygame.mixer.quit()	

				movie = pygame.movie.Movie(GameVideoPath)
				movie.set_volume(0.8)
				
				#VIDE FULLSCREEN
				#mrect = pygame.Rect((0,0),Resolution)

				mrect = pygame.Rect(WHERE_SNAP,SIZE_SNAP_CONVERT)
				movie.set_display(PyrScreen,mrect)


				movie.play()
				
				while movie.get_busy():
					evt = pygame.event.wait()
					if any( [  evt.type == JOYAXISMOTION,evt.type == JOYBUTTONDOWN, evt.type == QUIT,evt.type == KEYDOWN] ):
						T1=0
						T2=0
						movie.stop()
						movie=None 
						pygame.mixer.init()
						break
					pygame.display.flip()
		pygame.display.flip()
	return FrontEndGame,ExitStatus,FrontEndEmu,CptEmu
