:- dynamic(currentEvent/1).
:- dynamic(currentPlayer/1).
:- dynamic(buffer/1).

/**
 @desc returns the current Event
 @form currentEvent(Event)
 */
currentEvent(none).

/**
 @descr returns the current player
 @form currentPlayer(PlayerID)
 */
currentPlayer(yellow).


changeEvent(Event) :-
	retract(currentEvent(_)),
	assert(currentEvent(Event)).

validEvent(ID, Event) :-
	currentPlayer(ID),
	currentEvent(Event).

event(ID,nextPhase,_) :-
	currentPlayer(ID),
	lockPhase(false),
	!,
	changeEvent(none),
	nextPhase.

event(_,update,_) :-
	broadcastUpdate,
	!.

event(ID,Event,Args) :-
	validEvent(ID, Event),
	changeEvent(none),
	executeEvent(Event,Args).

% place ghost after drawing
executeEvent(placeGhost,[FieldID]) :-
	addGhost(FieldID),
	!.

% place ghost failed -> try again
executeEvent(placeGhost,_) :-
	addGhost.

% move taoist
executeEvent(move,[Pos]) :-
	executeMove(Pos),
	!.

% move taoist failed -> try again
executeEvent(move,_) :-
	phaseMove.

% what do you want to do next?
executeEvent(doNext,[Next]) :-
	phaseDecide(Next),
	!.

% impossible -> try again
executeEvent(doNext,_) :-
	phaseDecide.

% Do village action
executeEvent(village,Args) :-
	village(Args),
	!.

% village action failed -> try again 
executeEvent(village,_) :-
	village.

% ghost wanted taoist chosen
executeEvent(chooseTaoist,Args) :-
	buffer(From),
	fromGhost(From),
	ghostDoContinued(Args),
	!.

% vilalge wanted taoist chosen
executeEvent(chooseTaoist,Args) :-
	village(Args).

executeEvent(chooseOneMarker,Args) :-
	buffer(From),
	fromGhost(From),
	ghostDoContinued(Args),
	!.

executeEvent(chooseOneMarker,Args) :-
	village(Args).

% select ghost to fight against
executeEvent(ghostSelect,[Pos]) :-
	fight(Pos),
	!.

% fight failed -> select again
executeEvent(ghostSelect,_) :-
	fightStart.

% choose markers to defeat ghost
executeEvent(chooseMarkers,[WhiteDiceLeft,TaoMarkersLeft]) :-
	fight(WhiteDiceLeft,TaoMarkersLeft),
	!.

% choose markers failed -> try again
executeEvent(chooseMarkers,_) :-
	fightStart.

% place buddha
executeEvent(placeBuddha,[FieldID]) :-
	addBuddha(FieldID),
	!.

% place buddha failed -> try again
executeEvent(placeBuddha,_) :-
	phaseBuddha.

% continue ghost action
executeEvent(ghostDoContinue,Args) :-
	ghostDoContinued(Args),
	!.

% ghost action failed -> try again :-
executeEvent(ghostDoContinue,_) :-
	buffer((Action,GhostID)),
	ghostDo(GhostID,Action),
	!.

executeEvent(ghostDoContinue,_) :-
	buffer(Action),
	ghostDo(_,Action).
	

% Buffer
setBuffer(Content) :-
	retractall(buffer(_)),
	assert(buffer(Content)).

fromGhost(addQiAndYY).
fromGhost(addQiAndYY2).
fromGhost(curseDieAndAddQiAndYY).
fromGhost(curseDieAndAddQiAndYY2).
fromGhost(anyTao).
fromGhost(anyTwoTao).
fromGhost(stealTao).
