local liste=ahb.fichier.charge("tete/liste")

if liste==nil then liste={} 
else liste=textutils.unserialize(liste)
end

local ecran=ahb.addPeripheral("monitor_6")
local enclume=ahb.addPeripheral("enclumeCPO_0")
local coffre=ahb.addPeripheral("chest_0")
local w,h=ecran.pp.getSize()
local curs=1
local filtre=""
local filtreCopie=""
local affichage=true
local deCompt=0

function viewer(args,player)
	affichage=false
	filtre=args[2]
	filtreCopie=args[2]
	local total=0
	ecran.pp.clear()
	curs=0
	while not(curs==-1) do
		recherche(false)
		if not(curs==-1) then
			total=total+1
			afficheLigne()
		end
	end
	deCompt=3+(total*1.5)
	curs=0
	if total>h then
	--if total>1 then
		affichage=true
	end	
end
function viewerAdd(args,player)
	-- Envoyer une etiquette dans le coffre
	coffre.pp.condenseItems()
	coffre.pp.pushItem("WEST",1,1)
	
	-- Rename l ettiquette
	enclume.pp.rename(filtreCopie)
	
	table.insert(liste,filtreCopie)
	ahb.fichier.sauvegarde("tete/liste",textutils.serialize(liste))
end
function recherche(boucle)
	local r=true
	while r do
		cursPP(boucle)
		if curs==-1 then
			r=false
		else
			if string.match(liste[curs],filtre) then
				r=false
			end
		end
	end
end
function cursPP(boucle)
	curs=curs+1
	if liste[curs]==nil then
		if boucle then
			curs=1
		else
			curs=-1
		end
	end
end
function afficheLigne()	
	ecran.pp.scroll(1)
	ecran.pp.setCursorPos(1,h)
	ecran.pp.write(liste[curs])
end
function afficheLignes()
	curs=1
	while not(curs==-1) and curs<h do
		afficheLigne()
		cursPP(false)
	end
	if curs==-1 then
		curs=0
	end
end

chatbox.add("viewer",viewer,"//viewer PSEUDO chercher si le pseudo existe")
chatbox.add("add",viewerAdd,"//viewerAdd Creer la tete et ajoute a la liste le dernier PSEUDO chercher")

function init()
	afficheLignes()
	while true do
		if affichage then
			if filtre=="" then
				cursPP(true)
			else
				recherche(true)
			end
			afficheLigne()
		end
		if deCompt>0 then
			deCompt=deCompt-1
			if deCompt<=0 then
				afficheLignes()
				affichage=true
				filtre=""				
			end
		end
		os.sleep(1)
	end	
end