--main function 
--can return "exit"
function game()
	--the first time, place everything, but don't show cards (face down)
	--this is unneeded work as when starting a new game this will
	--be executed again but...
	--mainDeck=prepareMainDeck()
	fdebug("when starting main deck has "..tableLength(mainDeck).." cards")
	shuffleMainDeck()
	distributeCards()
	orderHands()
	disposePlayersAroundTheTable()
	positionAllCards()
	hideCardsOfPlayerNum(1) --other players have the cards already face down
	
	--init vars used to make the game progress
	activePlayer=1 --magic number :)
	findNextPlayer=false
	numberOfCardsPlayed=0
	powerOfCardsPlayed=NOVALUE
	waitingTurn=false
	nbPlayersInGame=0
	nbRanksAvailable=4
	ranks={}
	ranks[4]="president"
	ranks[3]="vice president"
	ranks[2]="vice asshole"
	ranks[1]="asshole"
	playEvent=false
	aGameIsRunning=false
	
	drawScene(screen, false)
	
	--the first time, open automaticaly the main menu
	local openMenu=false --true
	startNewGame(false)

	--the main loop
	while true do
		updateInputs(Controls.read())
		if openMenu or inputFirstPress("start") then
			openMenu=false
			local mmchoice=openMainMenu() --return can be: quitMenu cancel exit newGame
			drawScene(screen, false) --TODO: do it everytime?
			if mmchoice=="exit" then
				return "exit"
			elseif mmchoice=="newGame" then
				startNewGame()
			elseif mmchoice=="newNeutralGame" then
				startNewGame(true)
			end
		end
		
		if inputFirstPress("select") then
			snapshot()
		end
		
		if aGameIsRunning then
			playEvent=getPlayEvent(inputAnalogIsTouched() or inputIsPressed("triangle"))
	   	
		   	
		   	if playEvent~=nil then  --the AI has to play
		   		fdebug("")
		   		fdebug("#-----------------------------#")
		   		nbPlayersInGame=getNbPlayersInGame()
		   		--debugForced("nbPlayersInGame="..nbPlayersInGame)
		   		   		
		   		fdebug("activePlayer: "..activePlayer)
		   		debugHand(activePlayer)
				debugOnTheTable() --fdebug("on the table: "..numberOfCardsPlayed.."x "..powerOfCardsPlayed)
						   				   		
		   		if nbPlayersInGame==1 then
		   			--find smth to say
		   			say(players[activePlayer].position, getRandomSpeech("winRound"))
		   			
		   			powerOfCardsPlayed=NOVALUE
		   			numberOfCardsPlayed=0
		   			cleanTableDeck()
		   			putEveryoneWhoPassedInGameAgain()
		   			findNextPlayer=false
		   		else --nbplayersingame<>1
			   		if findNextPlayer==false then
				   		if handSize(activePlayer)==0 then
				   			powerOfCardsPlayed=NOVALUE
				   			numberOfCardsPlayed=0
				   			cleanTableDeck()
				   			players[activePlayer].state="finished"
				   			players[activePlayer].rank=ranks[nbRanksAvailable]
			   				nbRanksAvailable=nbRanksAvailable-1
				   			findNextPlayer=true
				   			
				   			-------here
				   			
				   			if stopGameIfNeeded() then
				   				startNewGame()
				   			end
				   		--trump is there since last event
				   		elseif powerOfCardsPlayed==TRUMP then
				   			powerOfCardsPlayed=NOVALUE
				   			numberOfCardsPlayed=0
				   			cleanTableDeck()
				   			waitingTurn=true
				   		end   		
			   		end
			   		
			   		if waitingTurn then
			   			--detect if players must be put in game again
						if powerOfCardsPlayed==NOVALUE then
							putEveryoneWhoPassedInGameAgain()
						end
			   			waitingTurn=false
			   		else--not a waiting turn
						local ai=AI()
						if ai==nil then
							fdebug("PASS")
							players[activePlayer].state="passed"
							say(players[activePlayer].position, getRandomSpeech("pass"))
						else --ai is not null
							debugAIResult(ai)
							
							--analyze what to say about the cards before putting them on the table
					   		local whatToSay=nil
					   		if numberOfCardsPlayed==0 then
					   			whatToSay=getRandomSpeech("startRound")
					   			--fdebug("startRound speech")
					   		else
					   			whatToSay=getSpeechAboutCards(ai)
					   		end
							
							makePlayerLeader(activePlayer)
							positionCards(players[activePlayer])
					   		numberOfCardsPlayed=tableLength(ai)
					   		powerOfCardsPlayed=ai[1].power
					   		
					   		putCardsOnTheTable(ai, activePlayer)
					   		
					   		if handSize(activePlayer)==0 then
					   			--say(players[activePlayer].position, "finished!!")
					   			
					   			--find something to say based on the rank
					   			whatToSay=nil
					   			if ranks[nbRanksAvailable]=="president" then
					   				whatToSay=getRandomSpeech("getPresident")
					   			elseif ranks[nbRanksAvailable]=="vice president" then
					   				whatToSay=getRandomSpeech("getVicePresident")
					   			elseif ranks[nbRanksAvailable]=="vice asshole" then
					   				whatToSay=getRandomSpeech("getViceAsshole")
					   			end
					   			say(players[activePlayer].position, whatToSay)
					   			
					   			
					   			findNextPlayer=false
					   			waitingTurn=true
					   		elseif powerOfCardsPlayed==TRUMP then
					   			say(players[activePlayer].position, getRandomSpeech("cut"))
					   			findNextPlayer=false
					   		else
					   			findNextPlayer=true
					   			waitingTurn=false
					   			
					   			say(players[activePlayer].position, whatToSay)
					   			
					   		end
						end
					end
				end
				
				
				if findNextPlayer and aGameIsRunning then
					activePlayer=nextAvailablePlayerNum(activePlayer)
				end
				
		   		fdebug("#-----------------------------#")
				fdebug("")
				
		   	end -- end the AI has to play
		end --end if aGameIsRunning
		
		--draw the scene
		drawScene(screen)		
		screen.waitVblankStart()
		screen.flip()
	end --end main loop
end












-------------------------------------
--
--	other functions
--
-------------------------------------

function showMessageBox(message)
	local bgimg=Image.createEmpty(480,272)
	drawScene(bgimg)
	messageBox(bgimg, message)
end

function openMainMenu()
	local bg=Image.createEmpty(480, 272)
	drawScene(bg)
	return mainMenu(bg, false) --return can be: quitMenu cancel exit
end

function drawScene(target, lazy)
	if lazy==nil then
		lazy=true
	end
	
	if lazy then
		drawGameBGBuffer(target)
		drawCardsOnTheTable(target)
		drawPlayers(target, true)
		drawIngameCursor(target)
		drawSpeechBubbles(target)
	else --not lazy, update the bgbuffer and draw lazy
		prepareGameBGBuffer()
		drawScene(target, true)
	end
end

--global
gameBGBuffer=Image.createEmpty(480,272)

function prepareGameBGBuffer() --call it update buffer?
	fdebug("prepareGameBGBuffer")
	drawCarpet(gameBGBuffer)
	drawPlayers(gameBGBuffer, false)
end

function drawGameBGBuffer(target)
	target:blit(0,0,gameBGBuffer,false)
	return target
end

--based on the number of cards in hand
function stopGameIfNeeded()
	local nbCardsInHands={}
	local i=1
	local nb0=0
	for i=1,4 do
		nbCardsInHands[i]=handSize(i)
		if nbCardsInHands[i]==0 then
			nb0=nb0+1
		end
	end
	
	if nb0>=3 then
		--3 players have 0 cards (or more?)
		--so it is the end of the game
		--find the one with cards in hand, he's the asshole!
		for i=1,4 do
			if nbCardsInHands[i]>0 then
				players[i].rank="asshole"
				say(players[i].position, getRandomSpeech("getAsshole"))
			end
			players[i].state="not_playing"
		end
		stopTimer()
		playEvent=false
		aGameIsRunning=false
		--TODO: blame player 1 if he's the asshole, or congrat him if pres.
		fdebug("end game\r\n")
		return true
	end
	return false
end


--initializes everything to make the game run
function startNewGame(neutralGame)
	--cleaning in case a game was interupted
	if aGameIsRunning and not neutralGame==true then --can be false or null
		--showMessageBox("game interrupted! everyone gets neutral again!")
		makeEveryOneNeutral()
	end
	--TODO: watch the ranks, and if there is a pb, put everyone in neutral state
	if neutralGame==true then
		makeEveryOneNeutral()
	end
	fdebug("on new game main deck has "..tableLength(mainDeck).." cards")
	--mainDeck=prepareMainDeck()
	cleanTableDeck()
	fdebug("after cleaning table deck main deck has "..tableLength(mainDeck).." cards")
	cleanHands()
	fdebug("after cleaning hands main deck has "..tableLength(mainDeck).." cards")
	
	if tableLength(mainDeck)~=118 then
		showMessageBox("main deck has "..tableLength(mainDeck).." cards")
	else
		--erase file
		alert("remove log file", 120)
		os.remove("debug.log")
	end
	
	shuffleMainDeck()
	distributeCards()
	orderHands()
	disposePlayersAroundTheTable()
	positionAllCards()
	
	--count total of cards in hands after distribution
	local tmpcount=handSize(1)+handSize(2)+handSize(3)+handSize(4)
	if tmpcount~=118 then
		showMessageBox("total amount of cards in hands is "..tmpcount.." cards")
	end
	
	--find the president, and if everyone is neutral, choose random
	activePlayer=playerNumByRank("president")

	findNextPlayer=true --watches if, when someone has played, we ask the
						--next player to play, or if he keeps the advantage
	numberOfCardsPlayed=0
	powerOfCardsPlayed=NOVALUE
	waitingTurn=false
	nbPlayersInGame=4
	nbRanksAvailable=4
	playEvent=false
	aGameIsRunning=true

	if activePlayer==nil then --no president, choosing a random player
		activePlayer=random(2,4)
		if activePlayer==1 then
			--showMessageBox("lucky! you start")
			alert("lucky! you start")
		else
			--showMessageBox("player "..activePlayer.." starts")
			alert("player "..activePlayer.." starts")
			say(players[activePlayer].position, getRandomSpeech("startsGameLucky"))
		end
	else
		local cardsToExchange={}
		cardsToExchange["president"]=getCardsToExchangeByRank("president")
		cardsToExchange["vice president"]=getCardsToExchangeByRank("vice president")
		cardsToExchange["vice asshole"]=getCardsToExchangeByRank("vice asshole")
		cardsToExchange["asshole"]=getCardsToExchangeByRank("asshole")
		local bg=Image.createEmpty(480, 272)
		drawScene(bg, false) --because players have moved, redraw everything
		exchangeCardsMenu(bg, cardsToExchange[exchangePartnerRankByRank(players[1].rank)], cardsToExchange[players[1].rank], true)
		addCardsToHandByRank(cardsToExchange["president"], "asshole")
		addCardsToHandByRank(cardsToExchange["asshole"], "president")
		addCardsToHandByRank(cardsToExchange["vice president"], "vice asshole")
		addCardsToHandByRank(cardsToExchange["vice asshole"], "vice president")
		orderHands()
		positionAllCards()
		
		if players[1].rank=="president" then
			--showMessageBox("president, you start")
			alert("president, you start")
		else
			--showMessageBox("the president starts")
			alert("the president starts")
			say(players[activePlayer].position, getRandomSpeech("startsGamePresident"))
		end
	end
	
	putEveryOneInState("in_game")
	
	--if activePlayer==1 then
	--	placeCursorOnCardNum(1)
		--makeCursorAvailable()
	--else
		startTimer()
	--end
end

function putEveryoneWhoPassedInGameAgain()
	for i=1,4 do
   		if players[i].state=="passed" then
   			players[i].state="in_game"
   		end
   	end
end

function debugAIResult(aiResult)
	local i=0
	local str="PLAYED: "
	for i=1, tableLength(aiResult) do
		if aiResult[i].power<=9 then
			str=str..aiResult[i].power
		elseif aiResult[i].power==10 then
			str=str.."X"
		elseif aiResult[i].power==11 then
			str=str.."V"
		elseif aiResult[i].power==12 then
			str=str.."C"
		elseif aiResult[i].power==13 then
			str=str.."D"
		elseif aiResult[i].power==14 then
			str=str.."R"
		elseif aiResult[i].power==15 then
			str=str.."A"
		elseif aiResult[i].power==16 then
			str=str.."2"
		else
			str=str.."*"
		end
	end
	fdebug(str)
end

function debugOnTheTable()
	local i=0
	local str="on the table: "..numberOfCardsPlayed.." x "
	
	if powerOfCardsPlayed<=9 then
		str=str..powerOfCardsPlayed
	elseif powerOfCardsPlayed==10 then
		str=str.."X"
	elseif powerOfCardsPlayed==11 then
		str=str.."V"
	elseif powerOfCardsPlayed==12 then
		str=str.."C"
	elseif powerOfCardsPlayed==13 then
		str=str.."D"
	elseif powerOfCardsPlayed==14 then
		str=str.."R"
	elseif powerOfCardsPlayed==15 then
		str=str.."A"
	elseif powerOfCardsPlayed==16 then
		str=str.."2"
	else
		str=str.."*"
	end
	fdebug(str)
end

function debugHand(playerNum)
	local i=0
	local str="in hand: "
	local sz=handSize(playerNum)
	for i=1, sz do
		if players[playerNum].hand[i].power<=9 then
			str=str..players[playerNum].hand[i].power
		elseif players[playerNum].hand[i].power==10 then
			str=str.."X"
		elseif players[playerNum].hand[i].power==11 then
			str=str.."V"
		elseif players[playerNum].hand[i].power==12 then
			str=str.."C"
		elseif players[playerNum].hand[i].power==13 then
			str=str.."D"
		elseif players[playerNum].hand[i].power==14 then
			str=str.."R"
		elseif players[playerNum].hand[i].power==15 then
			str=str.."A"
		elseif players[playerNum].hand[i].power==16 then
			str=str.."2"
		else
			str=str.."*"
		end
	end
	str=str.." ["..sz.."]"
	fdebug(str)
end








