---------------------------------------------------
------------------  variables  ---------------------
---------------------------------------------------
-- vars
report = " Please report to th_robert@hotmail.fr"
-- couleurs
blanc = pge.gfx.createcolor(255, 255, 255)
noir = pge.gfx.createcolor(0, 0, 0)
-- font
font = pge.font.load("gfx/lucida.ttf", 13, PGE_RAM)
if not font then
	error("Failed to load font.".. report)
end
font2 = pge.font.load("gfx/lucida_g.ttf", 13, PGE_RAM)
if not font then
	error("Failed to load font2.".. report)
end

---------------------------------------------------
------------------  Dossiers   --------------------
---------------------------------------------------

if not pge.dir.exists('ms0:/PSP') then
	pge.dir.mkdir('ms0:/PSP')
end
if not pge.dir.exists('ms0:/PSP/THEME') then
	pge.dir.mkdir('ms0:/PSP/THEME')
end
if not pge.dir.exists('ms0:/PSP/THEME') then
	pge.dir.mkdir('ms0:/PSP/THEME')
end
if not pge.dir.exists('previews') then
	pge.dir.mkdir('previews')
end
if not pge.dir.exists('previews_g') then
	pge.dir.mkdir('previews_g')
end

pge.controls.enable()

---------------------------------------------------
------------------  langue  -----------------------
---------------------------------------------------

-- si le fichier existe (langue deja definie)
if pge.file.exists("langue.lua") then
	langue_file = assert(loadfile("langue.lua"))
	if langue_file then
		langue_file()
		langue_file = nil
		collectgarbage("collect")
	else
		error("Failed to load language settings file.".. report)
	end
else
	langue = 1
	-- chargement des images
	langue_bg_fr = pge.texture.load("gfx/langue_fr.png")
	langue_bg_en = pge.texture.load("gfx/langue_en.png")
	-- boucle
	while pge.running() do
		pge.controls.update()
		
		-- blits
		pge.gfx.startdrawing()
		pge.gfx.clearscreen()
		if langue == 1 then
			langue_bg_fr:activate()
			langue_bg_fr:draweasy(0, 0)
		else
			langue_bg_en:activate()
			langue_bg_en:draweasy(0, 0)
		end
		pge.gfx.enddrawing()
		pge.gfx.swapbuffers()
		
		-- pad
		if pge.controls.pressed(PGE_CTRL_LEFT) or pge.controls.pressed(PGE_CTRL_RIGHT) then
			if langue == 1 then
				langue = 2
			else
				langue = 1
			end
		elseif pge.controls.pressed(PGE_CTRL_CROSS) then
			langue_bg_fr = nil
			langue_bg_en = nil
			break
		end
	end
	-- save langue
	langue_file = pge.file.open("langue.lua", PGE_FILE_CREATE + PGE_FILE_WRONLY)
	
	if langue == 1 then		langue_file:write("langue = 1")
	else					langue_file:write("langue = 2") end
	langue_file:close()
end

---------------------------------------------------
-------------  Download liste  --------------------
---------------------------------------------------

-- intialisation
if not pge.net.init() then
	error("Error on net init."..report)
end
if not pge.utils.netinit() then
	error("Error on net dialog init."..report)
end
state = -1
bg = pge.texture.load("gfx/fond.png")

-- verif connexion
while pge.running() do
	pge.controls.update()
	pge.gfx.startdrawing()
	pge.gfx.clearscreen()
	pge.gfx.enddrawing()
	state = pge.utils.netupdate()
	if state == 0 then
		break
	elseif state == 1 then
		pge.net.shutdown()
		break
	elseif state ~= PGE_UTILS_DIALOG_RUNNING then
		pge.net.shutdown()
		break
	end
	pge.gfx.swapbuffers()
end

while pge.running() do
	pge.controls.update()
	
	-- blits
	if pge.net.isconnected() then
		pge.gfx.startdrawing()
		pge.gfx.clearscreen()
		
		bg:activate()
		bg:draweasy(0, 0)
		
		if langue == 1 then
			font2:activate()
			font2:printcenter(95, noir, 'Telechargement et analyse de la liste de themes')
			font:activate()
			font:printcenter(110, noir, 'Patientez...')
		else
			font2:activate()
			font2:printcenter(95, noir, 'Downloading and analyzing list of themes')
			font:activate()
			font:printcenter(110, noir, 'Please wait...')
		end
		
		pge.gfx.enddrawing()
		pge.gfx.swapbuffers()
	else
		pge.gfx.startdrawing()
		pge.gfx.clearscreen()
		
		bg:activate()
		bg:draweasy(0, 0)
		
		if langue == 1 then
			font2:activate()
			font2:printcenter(95, noir, 'Erreur de connexion')
			font:activate()
			font:printcenter(110, noir, 'Appuyez sur Start pour quitter')
		else
			font2:activate()
			font2:printcenter(95, noir, 'Connexion error')
			font:activate()
			font:printcenter(110, noir, 'Press Start to quit')
		end
		
		pge.gfx.enddrawing()
		pge.gfx.swapbuffers()
		while not pge.controls.pressed(PGE_CTRL_START) do
			pge.controls.update()
		end
		pge.exit()
	end
	
	-- download
	if pge.net.isconnected() then
		dl_result = pge.net.getfile("http://trobert94.saina-lesite.com/401.lua", "themes.lua")
		pge.net.shutdown()
		break
	end
end

---------------------------------------------------
------------  Download miniatures  --------------
---------------------------------------------------

themes_dl_nbr = 0
themes_dl = {}
themes_dl_path = {}
themes_dl_num = {}

-- anamyse liste
if pge.file.exists("themes.lua") then
	theme_file = assert(loadfile("themes.lua"))
	if theme_file then
		theme_file()
		theme_file = nil
		collectgarbage("collect")
	else
		error("Failed to load themes list.".. report)
	end
else
	pge.gfx.startdrawing()
	pge.gfx.clearscreen()
	
	bg:activate()
	bg:draweasy(0, 0)
	
	if langue == 1 then
		font2:activate()
		font2:printcenter(95, noir, 'Liste de themes non existante')
		font:activate()
		font:printcenter(110, noir, 'Appuyez sur Start pour quitter')
	else
		font2:activate()
		font2:printcenter(95, noir, 'List of themes didn\'t exist')
		font:activate()
		font:printcenter(110, noir, 'Press Start to quit')
	end
	
	pge.gfx.enddrawing()
	pge.gfx.swapbuffers()
	while not pge.controls.pressed(PGE_CTRL_START) do
		pge.controls.update()
	end
	pge.exit()
end


-- miniatures a dl
i = 1
while i <= themes_nombre do
	if not pge.file.exists('previews/'..themes_path[i]..'_fr.png') or not pge.file.exists('previews/'..themes_path[i]..'_en.png')  then
		themes_dl[themes_dl_nbr + 1] = themes_noms[i]
		themes_dl_path[themes_dl_nbr + 1] = themes_path[i]
		themes_dl_num[themes_dl_nbr + 1] = themes_nombre - i
		themes_dl_nbr = themes_dl_nbr + 1
	end
	i = i + 1
end

-- reconnexion wifi
if not pge.net.init() then
	error("Error on net init."..report)
end
if not pge.utils.netinit() then
	error("Error on net dialog init."..report)
end
state = -1
bg = pge.texture.load("gfx/fond.png")

-- verif connexion
while pge.running() do
	pge.controls.update()
	pge.gfx.startdrawing()
	pge.gfx.clearscreen()
	pge.gfx.enddrawing()
	state = pge.utils.netupdate()
	if state == 0 then
		break
	elseif state == 1 then
		pge.net.shutdown()
		break
	elseif state ~= PGE_UTILS_DIALOG_RUNNING then
		pge.net.shutdown()
		break
	end
	pge.gfx.swapbuffers()
end

-- telechargmetn si necessaire
if themes_dl_nbr > 0 then
	while pge.running() do
		pge.controls.update()
		
		-- non connecte / connecte
		if not pge.net.isconnected() then
			pge.gfx.startdrawing()
			pge.gfx.clearscreen()
			
			bg:activate()
			bg:draweasy(0, 0)
			
			if langue == 1 then
				font2:activate()
				font2:printcenter(95, noir, 'Erreur de connexion')
				font:activate()
				font:printcenter(110, noir, 'Appuyez sur Start pour quitter')
			else
				font2:activate()
				font2:printcenter(95, noir, 'Connexion error')
				font:activate()
				font:printcenter(110, noir, 'Press Start to quit')
			end
			
			pge.gfx.enddrawing()
			pge.gfx.swapbuffers()
			while not pge.controls.pressed(PGE_CTRL_START) do
				pge.controls.update()
			end
			pge.exit()
		else
			i = 1
			while i <= themes_dl_nbr do
				-- minature fr
				pge.gfx.startdrawing()
				pge.gfx.clearscreen()
				
				bg:activate()
				bg:draweasy(0, 0)
				
				if langue == 1 then
					font2:activate()
					font2:printcenter(95, noir, 'Telechargement des miniatures')
					font:activate()
					font:printcenter(110, noir, i ..'/'.. themes_dl_nbr)
					font:printcenter(125, noir, themes_dl[i])
				else
					font2:activate()
					font2:printcenter(95, noir, 'Downloading previews')
					font:activate()
					font:printcenter(110, noir, i ..'/'.. themes_dl_nbr)
					font:printcenter(125, noir, themes_dl[i])
				end
				pge.gfx.enddrawing()
				pge.gfx.swapbuffers()
				dl_result = nil
				dl_result = pge.net.getfile('http://trobert94.saina-lesite.com/dl.php?fr_p='.. themes_dl_num[i], 'previews/'..themes_dl_path[i] .. '_fr.png')
				dl_result = nil
				dl_result = pge.net.getfile('http://trobert94.saina-lesite.com/dl.php?en_p='.. themes_dl_num[i], 'previews/'..themes_dl_path[i] .. '_en.png')
				i = i + 1
			end
			break
		end
	end
end

themes_dl_nbr = nil
themes_dl = nil
themes_dl_num = nil
themes_dl_path = nil
dl_result = nil
state = nil


-- blit d'info
pge.gfx.startdrawing()
pge.gfx.clearscreen()

bg:activate()
bg:draweasy(0, 0)

if langue == 1 then
	font2:activate()
	font2:printcenter(95, noir, 'Chargement des miniatures dans la RAM')
	font:activate()
	font:printcenter(110, noir, 'Patientez...')
else
	font2:activate()
	font2:printcenter(95, noir, 'Loading previews in the RAM')
	font:activate()
	font:printcenter(110, noir, 'Please wait...')
end
pge.gfx.enddrawing()
pge.gfx.swapbuffers()

bg = nil

---------------------------------------------------
------------  Affichage de la Liste  --------------
---------------------------------------------------

----------------------
-- vars
pos_txt_titres_x = 120
pos_txt_titres_y = 43

pos_txt_auteurs_x = 120
pos_txt_auteurs_y = 69

pos_img_prev_x = 5
pos_img_prev_y = 37

--pos_img_titres_x = 80
--pos_img_titres_y = 39

--pos_img_auteurs_x = 80
--pos_img_auteurs_y = 65

pos_img_img_x = 370
pos_img_img_y = 32

pos_img_img_s_x = 373
pos_img_img_s_y = 41

pos_img_dl_x = 420
pos_img_dl_y = 32

pos_img_dl_s_x = 431
pos_img_dl_s_y = 37

premiere_ligne = 1
lignes_imgs = {}
i = 1

----------------------
-- images
bg = pge.texture.load("gfx/liste.png")
img = pge.texture.load("gfx/img.png")
dl = pge.texture.load("gfx/dl.png")
img_sel = pge.texture.load("gfx/img_sel.png")	-- alpha : 140
dl_sel = pge.texture.load("gfx/dl_sel.png")		-- alpha : 140
menu = pge.texture.load("gfx/menu.png")			-- alpha : 220
sel = pge.texture.load("gfx/sel.png")			-- alpha : 180
col = 1
ligne = 1
choix = 1
afficher_menu = 0

----------------------
-- load previews
while i <= 4 do
	if langue == 1 then
		lignes_imgs[i] = pge.texture.load("previews/"..themes_path[i] .."_fr.png")
	else
		lignes_imgs[i] = pge.texture.load("previews/"..themes_path[i] .."_en.png")
	end
	i = i + 1
end

----------------------
-- affichage
while pge.running() do
	----------------------
	--  pad
	----------------------
	pge.controls.update()
	--if afficher_menu == 0 then
		if pge.controls.pressed(PGE_CTRL_LEFT) or pge.controls.pressed(PGE_CTRL_RIGHT) then
			if col == 1 then
				col = 2
			else
				col = 1
			end
		elseif pge.controls.pressed(PGE_CTRL_DOWN) then
			ligne = ligne + 1
		elseif pge.controls.pressed(PGE_CTRL_UP) then
			ligne = ligne - 1
		elseif pge.controls.pressed(PGE_CTRL_CROSS) then
			if col == 1 then
				-- dl preview
				if pge.net.isconnected() then
					num_ligne_a_faire = premiere_ligne + ligne - 1
					if langue == 1 then
						pge.gfx.startdrawing()
						menu:activate()
						menu:draweasy(0, 0, 0, 220)
						font:activate()
						font:printcenter(100, noir, "Telechargement de la preview en cours")
						font:printcenter(115, noir, "Patientez...")
						pge.gfx.enddrawing()
						pge.gfx.swapbuffers()
						
						if not pge.file.exists('previews_g/'.. themes_path[num_ligne_a_faire] ..'_fr.png') then
							dl_result = pge.net.getfile('http://trobert94.saina-lesite.com/dl.php?fr_g='..themes_nombre - num_ligne_a_faire, 'previews_g/'.. themes_path[num_ligne_a_faire] ..'_fr.png')
						end
						preview_dl = pge.texture.load('previews_g/'.. themes_path[num_ligne_a_faire] ..'_fr.png')
						
						pge.gfx.startdrawing()
						pge.gfx.clearscreen()
						preview_dl:activate()
						preview_dl:draweasy(0, 0)
						font2:activate()
						font2:print(5, 257, noir, "Appuyez sur Start pour retourner a la liste")
						pge.gfx.enddrawing()
						pge.gfx.swapbuffers()
						
						while not pge.controls.pressed(PGE_CTRL_START) do
							pge.controls.update()
						end
						
						preview_dl = nil
					else
						pge.gfx.startdrawing()
						menu:activate()
						menu:draweasy(0, 0, 0, 220)
						font:activate()
						font:printcenter(100, noir, "Downloading preview")
						font:printcenter(115, noir, "Please wait...")
						pge.gfx.enddrawing()
						pge.gfx.swapbuffers()
						
						if not pge.file.exists('previews_g/'.. themes_path[num_ligne_a_faire] ..'_en.png') then
							dl_result = pge.net.getfile('http://trobert94.saina-lesite.com/dl.php?en_g='..themes_nombre - num_ligne_a_faire, 'previews_g/'.. themes_path[num_ligne_a_faire] ..'_en.png')
						end
						preview_dl = pge.texture.load('previews_g/'.. themes_path[num_ligne_a_faire] ..'_en.png')
						
						pge.gfx.startdrawing()
						pge.gfx.clearscreen()
						preview_dl:activate()
						preview_dl:draweasy(0, 0)
						font2:activate()
						font2:print(5, 257, noir, "Press Start to return to the list")
						pge.gfx.enddrawing()
						pge.gfx.swapbuffers()
						
						while not pge.controls.pressed(PGE_CTRL_START) do
							pge.controls.update()
						end
						
						preview_dl = nil
					end
				end
			else
				if pge.net.isconnected() then
					if langue == 1 then
						pge.gfx.startdrawing()
						menu:activate()
						menu:draweasy(0, 0, 0, 220)
						font:activate()
						font:printcenter(100, noir, "Telechargement du theme en cours")
						font:printcenter(115, noir, "Patientez...")
						pge.gfx.enddrawing()
						pge.gfx.swapbuffers()
					else
						pge.gfx.startdrawing()
						menu:activate()
						menu:draweasy(0, 0, 0, 220)
						font:activate()
						font:printcenter(100, noir, "Downloading theme")
						font:printcenter(115, noir, "Please wait...")
						pge.gfx.enddrawing()
						pge.gfx.swapbuffers()
					end
					
					num_ligne_a_faire = premiere_ligne + ligne - 1
					dl_result = pge.net.getfile('http://trobert94.saina-lesite.com/dl.php?n='..themes_nombre - num_ligne_a_faire, 'ms0:/PSP/THEME/'.. themes_noms[num_ligne_a_faire] ..'.ctf')
				end
			end
		elseif pge.controls.pressed(PGE_CTRL_START) then
			afficher_menu = 1
		end
	-- else
		-- if pge.controls.pressed(PGE_CTRL_DOWN) then
			-- choix = choix + 1
		-- elseif pge.controls.pressed(PGE_CTRL_UP) then
			-- choix = choix - 1
		-- elseif pge.controls.pressed(PGE_CTRL_CROSS) then
			-- if choix == 1 then
				-- if pge.net.isconnected() then
					-- dl_result = pge.net.getfile('http://trobert94.saina-lesite.com/rars/cxmb.zip', 'cxmb.zip')
				-- end
			-- elseif choix == 2 then
				-- afficher_menu = 0
			-- else
				-- pge.exit()
			-- end
		-- elseif pge.controls.pressed(PGE_CTRL_START) then
			-- afficher_menu = 0
		-- end
	--end
	
	-- choxi menu
	-- if choix == 0 then
		-- choix = 3
	-- elseif choix == 4 then
		-- choix = 1
	-- end
	
	-- actualisation de la lsite
	if ligne == 5 then
		-- si on est pas a la fin de la lsite
		if (premiere_ligne + 3) < themes_nombre then
			premiere_ligne = premiere_ligne + 1
			lignes_imgs[1] = lignes_imgs[2]
			lignes_imgs[2] = lignes_imgs[3]
			lignes_imgs[3] = lignes_imgs[4]
			if langue == 1 then
				lignes_imgs[4] = pge.texture.load("previews/"..themes_path[premiere_ligne + 3] .."_fr.png")
			else
				lignes_imgs[4] = pge.texture.load("previews/"..themes_path[premiere_ligne + 3] .."_en.png")
			end
		end
		ligne = 4
	end
	-- si on est pas au debut de la lsite
	if ligne == 0 then
		if premiere_ligne > 1 then
			premiere_ligne = premiere_ligne - 1
			lignes_imgs[4] = lignes_imgs[3]
			lignes_imgs[3] = lignes_imgs[2]
			lignes_imgs[2] = lignes_imgs[1]
			if langue == 1 then
				lignes_imgs[1] = pge.texture.load("previews/"..themes_path[premiere_ligne] .."_fr.png")
			else
				lignes_imgs[1] = pge.texture.load("previews/"..themes_path[premiere_ligne] .."_en.png")
			end
		end
		ligne = 1
	end
	
	
	-- blit
	pge.gfx.startdrawing()
	pge.gfx.clearscreen()
	bg:activate()
	bg:draweasy(0, 0)
	i = 1
	while i <= 4 do
		num_ligne_a_faire = premiere_ligne + i - 1
		-- img
		lignes_imgs[i]:activate()
		lignes_imgs[i]:draweasy(pos_img_prev_x, (pos_img_prev_y + (60 * i) - 60))
		
		-- nom
		font2:activate()
		font2:print(pos_txt_titres_x, (pos_txt_titres_y + (60 * i) - 60), noir, themes_noms[num_ligne_a_faire])
		
		-- auteur
		font:activate()
		font:print(pos_txt_auteurs_x, (pos_txt_auteurs_y + (60 * i) - 60), noir, themes_auteurs[num_ligne_a_faire])
		
		--  blits de selection
		if ligne == i then
			if col == 1 then
				img_sel:activate()
				img_sel:draweasy(pos_img_img_s_x,(pos_img_img_s_y + (60 * i) - 60), 0, 140)
				img:activate()
				img:draweasy(pos_img_img_x, (pos_img_img_y + (60 * i) - 60))
			else
				dl_sel:activate()
				dl_sel:draweasy(pos_img_dl_s_x, (pos_img_dl_s_y + (60 * i) - 60), 0, 140)
				dl:activate()
				dl:draweasy(pos_img_dl_x, (pos_img_dl_y + (60 * i) - 60))
			end
		end
		i = i + 1
	end
	font:activate()
	font:print(400, 5, noir, themes_nombre.." themes")
	
	-- menu
	-- if afficher_menu == 1 then
		-- menu:activate()
		-- menu:draweasy(0, 0, 0, 220)
		-- sel:activate()
		-- if choix == 1 then
			-- sel:draweasy(0, 85, 0, 180)
		-- elseif choix == 2 then
			-- sel:draweasy(0, 195, 0, 180)
		-- else
			-- sel:draweasy(0, 215, 0, 180)
		-- end
		-- font:activate()
		-- if langue == 1 then
			-- font:printcenter(90, noir, "Telecharger et installer CXMB 3.2.1")
			-- font:printcenter(200, noir, "Retourner a la liste")
			-- font:printcenter(220, noir, "Quitter")
		-- else
			-- font:printcenter(90, noir, "Download and install CXMB 3.2.1")
			-- font:printcenter(200, noir, "Return to the list")
			-- font:printcenter(220, noir, "Exit")
		-- end
	-- end
	
	pge.gfx.enddrawing()
	pge.gfx.swapbuffers()
end

pge.net.shutdown()
bg = nil
pos_txt_titres = nil
pos_txt_auteurs = nil
pos_img_prev = nil
pos_img_titres = nil
pos_img_auteurs = nil
lignes = nil
i = nil
lignes_imgs = nil
font = nil
img = nil
dl = nil
img_sel = nil
dl_sel = nil
