#!/usr/bin/env python3

global cpt
global Origcpt
global EmuMod
global RomCpt
global MaxRomCpt
global CurentEmu

FirstRun = 1
cpt = 0
RomCpt =0
import configparser
from collections import Counter
from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk
import PIL.Image
import PIL.ImageTk
import sys
from modules.arrow import *
from modules.emulateur_display import *
import time
import os
#sys.path.append( './modules/')
#from arrow import *


#EmuMod :
# 	0 : Emu select
# 	1 : Rom select



#def EmuMod():



def ViewRom(EmuName,RomCpt):

	print("Canevas ROM MEDIA  : " + str(Cnv.find_all()))

	for IdCanvas in Cnv.find_all():
		if IdCanvas != 1:
			Cnv.delete(IdCanvas)
	BackgroundRom(str(CurentEmu))
	print("DEBUG MAX ROM: " + str(MaxRomCpt))

	WheelEmu="./data/roms/"+str(EmuName)+"/media/wheel/" + str(EmuName) + "_wheel.png"
	IsWheelEmu = IsFileExist(WheelEmu,"wheelemu")
	OpenWheelEmu=Image.open(IsWheelEmu)
	ResizeOpenWheelEmu=OpenWheelEmu.resize((RomUpSquareSizeX,RomUpSquareSizeY))
	TkOpenWheelEmu=ImageTk.PhotoImage(ResizeOpenWheelEmu)
	LabelResizeOpenWheelEmu=Label(arkadeus, image=TkOpenWheelEmu)
	LabelResizeOpenWheelEmu.TkOpenWheelEmu = TkOpenWheelEmu

	Wheel="./data/roms/"+str(EmuName)+"/media/wheel/" + str(RomRes[RomCpt]) + ".png"
	print("Wheel : "+ Wheel)
	IsWheel = IsFileExist(Wheel,"wheelemu")
	OpenWheel=Image.open(IsWheel)
	ResizeOpenWheel=OpenWheel.resize((RomMiddleSquareSizeX,RomMiddleSquareSizeY))
	TkOpenWheel=ImageTk.PhotoImage(ResizeOpenWheel)
	LabelResizeOpenWheel=Label(arkadeus, image=TkOpenWheel)
	LabelResizeOpenWheel.TkOpenWheel = TkOpenWheel

	Wheel="./data/roms/"+str(EmuName)+"/media/wheel/" + str(RomRes[RomCpt]) + ".png"
	IsWheel = IsFileExist(Wheel,"wheelemu")
	OpenWheel=Image.open(IsWheel)
	ResizeOpenWheel=OpenWheel.resize((RomBottomSquareSizeX,RomBottomSquareSizeY))
	TkOpenWheel=ImageTk.PhotoImage(ResizeOpenWheel)
	LabelResizeOpenWheel=Label(arkadeus, image=TkOpenWheel)
	LabelResizeOpenWheel.TkOpenWheel = TkOpenWheel

	Text="./data/roms/"+str(EmuName)+"/media/doc/" + str(RomRes[RomCpt]) + ".txt"
	IsText = IsFileExist(Text,"doc")
	with open(IsText, 'rb') as RomFile:
		DataRomFile = RomFile.read().rstrip()

	SnapEmu="./data/roms/"+str(EmuName)+"/media/snap/" + str(RomRes[RomCpt]) + ".png"
	IsSnapEmu = IsFileExist(SnapEmu,"snap")
	OpenSnapEmu=Image.open(IsSnapEmu)
	ResizeOpenSnapEmu=OpenSnapEmu.resize((RomLeftSquareSizeX,RomLeftSquareSizeY))
	TkOpenSnapEmu=ImageTk.PhotoImage(ResizeOpenSnapEmu)
	LabelResizeOpenSnapEmu=Label(arkadeus, image=TkOpenSnapEmu)
	LabelResizeOpenSnapEmu.TkOpenSnapEmu = TkOpenSnapEmu

	BoxText=Cnv.create_text(RomBottomSquareX,RomBottomSquareY,width= RomBottomSquareSizeX, text=DataRomFile,fill="white",font="Times 20 bold")
	BoxRect=Cnv.create_rectangle(RomBottomSquareTxtUpX,RomBottomSquareTxtUpY,RomBottomSquareTxtBottomX,RomBottomSquareTxtBottomY ,fill='black')
	Cnv.tag_lower(BoxRect,BoxText)
	Cnv.create_image(RomUpSquareX, RomUpSquareY, image=TkOpenWheelEmu)
	Cnv.create_image(RomMiddleSquareX, RomMiddleSquareY, image=TkOpenWheel)
	#Cnv.create_image(RomBottomSquareX, RomBottomSquareY, image=TkOpenWheel)
	Cnv.create_image(RomLeftSquareX, RomLeftSquareY, image=TkOpenSnapEmu)

	Cnv.pack(fill = "both", expand = True)


def BackgroundRom(Emu):


	print("Canevas ROM : " + str(Cnv.find_all()))

	

	EmuBgFile = "./data/emu/media/" + str(Emu) +"_bg.png"
	EmuBgFile = IsFileExist(EmuBgFile,"bg")

	OpenEmuBgfile=Image.open(EmuBgFile)
	PhotoEmuBgFile=OpenEmuBgfile.resize((Xsize,Ysize))
	TkPhotoEmuBgFile=ImageTk.PhotoImage(PhotoEmuBgFile)
	LabelEmuBgFile=Label(arkadeus, image=TkPhotoEmuBgFile)
	LabelEmuBgFile.TkPhotoEmuBgFile = TkPhotoEmuBgFile
	Cnv.create_image(0, 0, image=TkPhotoEmuBgFile, anchor = "nw")


def IsFileExist(AbsPathFile,TypeMedia):
	if not os.path.exists(AbsPathFile):
		match TypeMedia:
			case "emu":
				return "./media/noemu.png"
			case "bg":
				return "./media/nobg.png"
			case "wheel":
				return "./media/nowheel.png"
			case "snap":
				return "./media/nosnap.png"
			case "wheelemu":
				return "./media/nowheelemu.png"	
			case "doc":
				return "./media/nodoc.txt"
	else:
		return AbsPathFile
			
def BackgroundEmu():

	BackgroundEmu = Media["background"]
	BgEmu = PhotoImage(file = Background)
	LabelBgEmu = Label(arkadeus,image=BgEmu)
	LabelBgEmu.BgEmu = BgEmu
	Cnv.create_image( 0, 0, image = BgEmu, anchor = "nw")

def EnterEmu(GetEmuMod):
	global EmuMod
	global cpt
	global RomCpt
	RomCpt=0
	if GetEmuMod == 0:
		RomCpt = 1
		EmuMod = 1
		print("Emu : " + str(CurentEmu))
		#Cnv.delete("all")
		#BackgroundRom(str(CurentEmu))
		GenRomListPerGame(str(CurentEmu))


		#if RomCpt > MaxRomCpt:
		#	RomCpt = 0
		print("ENTER MODE : " + str(EmuRes[RomCpt]) + " ID :" +  str(RomCpt))
		ViewRom(CurentEmu,RomCpt)

	
def ViewEmu(cL,xL,yL,cM,xM,yM,cR,xR,yR):
	NfL="./data/emu/media/" + EmuRes[cL] + ".png"
	NfL = IsFileExist(NfL,"emu")
	NfM="./data/emu/media/" + EmuRes[cM] + ".png"
	NfM = IsFileExist(NfM,"emu")
	NfR="./data/emu/media/" + EmuRes[cR] + ".png"
	NfR = IsFileExist(NfR,"emu")


	OpenNfL=Image.open(NfL)
	PhotoNfL=OpenNfL.resize((Square,Square))
	TkNfL=ImageTk.PhotoImage(PhotoNfL)
	LabelPNfL=Label(arkadeus, image=TkNfL)
	LabelPNfL.TkNfL = TkNfL

	OpenNfM=Image.open(NfM)
	PhotoNfM=OpenNfM.resize((Square,Square))
	TkNfM=ImageTk.PhotoImage(PhotoNfM)
	LabelPNfM=Label(arkadeus, image=TkNfM)
	LabelPNfM.TkNfM = TkNfM

	OpenNfR=Image.open(NfR)
	PhotoNfR=OpenNfR.resize((Square,Square))
	TkNfR=ImageTk.PhotoImage(PhotoNfR)
	LabelPNfR=Label(arkadeus, image=TkNfR)
	LabelPNfR.TkNfR = TkNfR

	Cnv.pack(fill = "both", expand = True)
	for IdCanvas in Cnv.find_all():
		if IdCanvas != 1:
			Cnv.delete(IdCanvas)

	print (str(xL) + ":" + str(yL))
	Cnv.create_image(xL, yL, image=TkNfL)
	Cnv.create_image(xM, yM, image=TkNfM)
	Cnv.create_image(xR, yR, image=TkNfR)
	print("Curent Emu : " + str(EmuRes[cM]))

def leftKey(GetEmuMod):
	if GetEmuMod == 0:
		global CurentEmu
		global cpt
		cpt =  cpt - 1
		if cpt < 0:
			cpt = EmuCpt
		Lcpt = cpt
		Mcpt = cpt + 1
		Rcpt = cpt + 2
		if Mcpt > EmuCpt:
			Mcpt = 0
			Rcpt = 1
		if Rcpt > EmuCpt:
			Rcpt = 0
		print("DEBUG : " + str(EmuMod) + " Emu : " + str(cpt))
		CurentEmu = EmuRes[Mcpt]
		ViewEmu(Lcpt,EmuLeftSquareX, EmuLeftSquareY,Mcpt,EmuMiddleSquareX, EmuMiddleSquareY,Rcpt,EmuRightSquareX, EmuRightSquareY)
	if GetEmuMod == 1:
		global RomCpt
		RomCpt=RomCpt - 1
		if RomCpt < 0:
			RomCpt =  MaxRomCpt
		print("Running -  : " + str(RomCpt) + " ROM : " + str(RomRes[RomCpt]))
		ViewRom(CurentEmu,RomCpt)

def rightKey(GetEmuMod):

	if GetEmuMod == 0:
		global CurentEmu
		global cpt
		cpt = cpt + 1
		if cpt > EmuCpt:
			cpt = 0
		Lcpt = cpt
		Mcpt = cpt + 1
		Rcpt = cpt + 2
		if Mcpt > EmuCpt:
			Mcpt = 0
			Rcpt = 1
		if Rcpt > EmuCpt:
			Rcpt = 0
		print("DEBUG : " + str(EmuMod) + " Emu : " + str(cpt))
		ViewEmu(Lcpt,EmuLeftSquareX, EmuLeftSquareY,Mcpt,EmuMiddleSquareX, EmuMiddleSquareY,Rcpt,EmuRightSquareX, EmuRightSquareY)
		CurentEmu = EmuRes[Mcpt]
	if GetEmuMod == 1:
		global RomCpt
		RomCpt=RomCpt + 1
		if RomCpt > MaxRomCpt:
			RomCpt =  0
		print("Running +  : " + str(RomCpt) + " ROM : " + str(RomRes[RomCpt]))

		ViewRom(CurentEmu,RomCpt)


def Escape(GetEmuMod):
	if GetEmuMod == 0:
		print("Ciao !!")
		arkadeus.quit()
	if GetEmuMod == 1:
		global EmuMod
		global cpt
		EmuMod = 0
		cpt = 0


		BackgroundEmu()
		ViewEmu(0,EmuLeftSquareX, EmuLeftSquareY,1,EmuMiddleSquareX, EmuMiddleSquareY,2,EmuRightSquareX, EmuRightSquareY)



def GenEmuList():
	global EmuRes
	dir_path = r'./data/emu/bin/'
	for path in os.listdir(dir_path):
		if os.path.isfile(os.path.join(dir_path, path)):
			FileName=os.path.splitext(path)[0]
			EmuRes.append(FileName)
			print("DEBUG : " + FileName)

	cnt = Counter(EmuRes)
	global EmuCpt
	EmuCpt=len(cnt) - 1
	print(" Nmbre emulateur : " + str(EmuCpt))


def GenRomListPerGame(Emu):
	global RomRes
	RomRes.clear()
	print("DEBUG Gen List ROM : " + str(Emu))
	DirRomPath='./data/roms/'+Emu+'/roms'
	dir_rom_path = r''+DirRomPath

	isDirRom = os.path.isdir(DirRomPath)
	print ("Dir : " + DirRomPath + " : status:" + str(isDirRom))
	if isDirRom == True:

		for RomFile in os.listdir(dir_rom_path):
			if os.path.isfile(os.path.join(dir_rom_path, RomFile)):
				RomFileName=os.path.splitext(RomFile)[0]
				RomRes.append(RomFileName)
				print("DEBUG : " + RomFileName)

		cntrom = Counter(RomRes)
		global RomCpt
		global MaxRomCpt
		MaxRomCpt=len(cntrom) - 1
		print("Nmbre de roms : " + str(MaxRomCpt))
		print ("ListROms : " + str(RomRes))
		print ("TEST 1942 : " + str(RomRes[0]) )


arkadeus= Tk()

global EmuRes 
global RomRes

EmuRes = []
RomRes = []

EmuMod = 0

GenEmuList()

config_obj = configparser.ConfigParser()
config_obj.read("./conf/config.ini")
Media = config_obj["Media"]
ForceRes = Media["force_resolution"]
Background = Media["background"]
Square = int(Media["square_size"])

config_rom = configparser.ConfigParser()
config_rom.read("./conf/games.ini")

Emulateur = config_rom["emulateurs"]

print(Emulateur["EmulateurList"])
IdEmu(Emulateur["EmulateurList"])


arkadeus.attributes('-fullscreen', True)
arkadeus.title("Arkadeus")



if ForceRes == "y":
	Xsize = int(Media["x_resolution"])
	Ysize = int(Media["y_resolution"])
else:
	Xsize = arkadeus.winfo_screenwidth()
	Ysize = arkadeus.winfo_screenheight()


################ Carto Emu Mode ####################
EmuMiddleSquareX=(Xsize/2)
EmuMiddleSquareY=(Ysize/2)

EmuLeftSquareX=(Xsize/3)
EmuLeftSquareY=(Ysize/3)

EmuRightSquareX=(Xsize*2/3)
EmuRightSquareY=(Ysize/3)

################ Carto Rom Mode ####################

RomIndice = 40

#RomIndiceX = round(Xsize / RomIndice)
#RomIndiceY = round(Ysize / RomIndice)

RomIndiceX = RomIndice
RomIndiceY = RomIndice

RomUpSquareX=RomIndiceX
RomUpSquareY=RomIndiceY

RomUpSquareSizeX=round(((Xsize-(RomIndiceX*3))/2))
RomUpSquareSizeY=round(((Ysize-(RomIndiceY*4))/3))
RomUpSquareX=round(RomIndiceX + RomUpSquareSizeX/2)
RomUpSquareY=round(RomIndiceY + RomUpSquareSizeY/2)

RomMiddleSquareSizeX=RomUpSquareSizeX
RomMiddleSquareSizeY=RomUpSquareSizeY
RomMiddleSquareX=RomUpSquareX
RomMiddleSquareY=RomUpSquareY*2 + RomUpSquareSizeY/2

RomBottomSquareSizeX=RomUpSquareSizeX
RomBottomSquareSizeY=RomUpSquareSizeY
RomBottomSquareX=RomUpSquareX
RomBottomSquareY=RomUpSquareY*3 + RomUpSquareSizeY 

RomBottomSquareTxtUpX=RomIndiceX
RomBottomSquareTxtUpY= RomIndiceY*3+RomUpSquareSizeY*2

RomBottomSquareTxtBottomX=RomBottomSquareTxtUpX + RomBottomSquareSizeX
RomBottomSquareTxtBottomY=RomBottomSquareTxtUpY +RomUpSquareSizeY 


RomLeftSquareSizeX=RomUpSquareSizeX - RomIndiceX
RomLeftSquareSizeY=round((Ysize-(RomIndiceY*2)))
RomLeftSquareX=RomIndiceX+ RomLeftSquareSizeX/2 + Xsize/2
RomLeftSquareY=round(RomIndiceY + RomLeftSquareSizeY/2)

####################################################





Cnv = Canvas( arkadeus, width = Ysize , height = Xsize)
Cnv.pack(fill = "both", expand = True)

if EmuMod == 0:
	BackgroundEmu()
	ViewEmu(cpt,EmuLeftSquareX, EmuLeftSquareY,cpt+1,EmuMiddleSquareX, EmuMiddleSquareY,cpt+2,EmuRightSquareX, EmuRightSquareY)

if EmuMod == 1:
	ViewEmu(cpt,EmuLeftSquareX, EmuLeftSquareY,cpt+1,EmuMiddleSquareX, EmuMiddleSquareY,cpt+2,EmuRightSquareX, EmuRightSquareY)



arkadeus.bind("<Left>", lambda event: leftKey(EmuMod))
arkadeus.bind("<Right>", lambda event: rightKey(EmuMod))
arkadeus.bind("<Return>", lambda event: EnterEmu(EmuMod))
arkadeus.bind('<Escape>',lambda event : Escape(EmuMod))

arkadeus.mainloop()
