extends Node

var turn = 0;
var players = [];
var player = "res://Scenes/player/Player.tscn";
var baseDirStatus = "res://Scenes/status/";
var baseDirResponses = "res://Scenes/responses/";
onready var GameNode = get_tree().get_root();
var pInstance;
var currentPlayer = 0;
var hcontainer;
var playerPlaying;
var winner;
var fin = false;

func _ready():

	EventsManager.init();
	pInstance = load(player);
	return;

func startGame():
	playerPlaying = false;
	nextTurn();
	updateStatus();

func nextTurn():
	turn += 1;

func updateStatus():
	var parent = get_tree().get_root().find_node("HUD", true, false);
	var turnLabel = parent.get_node("turn");
	turnLabel.set_text(str("Joueur : ", currentPlayer, " / tour : ", turn));

func nextPlayer():
	var hud = get_tree().get_root().find_node("HUD", true, false);

	if !playerPlaying:

		hud.greyPlayer(bool(currentPlayer), false);
		hud.greyPlayer(!bool(currentPlayer), true);

		print(players[currentPlayer].rage);
		print(players[currentPlayer].money);
		print(players[currentPlayer].frustration);
		var previousPlayer = currentPlayer;
		if currentPlayer == 1:

			currentPlayer = 0;
			nextTurn();
		else :
			currentPlayer = 1;

		if !players[currentPlayer].canPlay:
			currentPlayer = previousPlayer;
		updateStatus();
		if rand_range(0, 1) > 0.7:
			pickEvent()
			playerPlaying = true;
	else:
		return;

func registerPlayer(className):
	var p = pInstance.instance();
	players.push_back(p);
	p.init(className);
	GameNode.add_child(p);

func hideEvent():
	var parent = get_tree().get_root().find_node("HUD", true, false);
	var animations = get_tree().get_root().find_node("Animations", true, false);

	animations.play("EventFadeOut");
	playerPlaying = false;

func endGame(playerDed, causeOfDed):
	if fin:
		return;
	fin = true;
	var aBar = get_tree().get_root().find_node("HUD", true, false).get_node("ActionBar");
	aBar.hide();
	var parent = get_tree().get_root().find_node("HUD", true, false);
	var sprite = parent.get_node("TextureRect");
	var res = parent.get_node("rootResponses");
	var desc = parent.get_node("rootDescription");

	winner = players[(playerDed + 1) % 2].className

	if causeOfDed == 1:
		sprite.set_texture(load("res://assets/img/cards/banqueroute.png"));
		desc.set_text("fBanqueRoute");

	elif causeOfDed == 2:
		sprite.set_texture(load("res://assets/img/cards/victoireroyale.png"));
		desc.set_text("IlcKC");

	elif causeOfDed == 3:
		sprite.set_texture(load("res://assets/img/cards/KCLaMaison.png"));
		desc.set_text("KCLaMaison");

	res.hide();
	sprite.show();
	desc.show();
	var animations = get_tree().get_root().find_node("Animations", true, false);

	animations.play("EventFadeIn");

	var timer = Timer.new();
	timer.connect("timeout", self, "_go_back_to_menu")
	timer.set_wait_time(3)
	timer.set_one_shot(true)
	add_child(timer)
	timer.start()

func _go_back_to_menu():
	SceneManager.game_ended(winner)

func pickEvent():
	if fin :
		return;
	if !players[currentPlayer].canPlay:
		print("joueur ", currentPlayer, " passe son tour");
		return;

	var tags = ["neutral", players[currentPlayer].className]
	var event = EventsManager.pullFromTag(tags);

	print(event.name)

	var assetRoot = "res://assets/img/cards/"
	var parent = get_tree().get_root().find_node("HUD", true, false);
	var animations = get_tree().get_root().find_node("Animations", true, false);

	var hud = parent.get_node("rootResponses");
	var Desc = parent.get_node("rootDescription");
	var sprite = parent.get_node("TextureRect");

	sprite.show();
	hud.show();
	Desc.show();
	Desc.bbcode_text = str("[center]", event.description, "[/center]");
	sprite.set_texture(load(str(assetRoot, event.asset)));

	if event.has("response") :
		hcontainer = HBoxContainer.new();
		hud.add_child(hcontainer);
		var responses = event.response;
		for i in responses:
			instanciateResponses(i);
		hcontainer.alignment = HALIGN_CENTER;


	if event.has("effects") :
		var eventEffects = event.effects;
		for i in eventEffects:
			applyEffect(i);

	if event.has("status") :
		var statusEffects = event.status;
		for i in statusEffects:
			instanciateStatus(i);
	animations.play("EventFadeIn");

func applyEffect(effect):
	var target = effect.target;
	var targetId = -1;

	var statTarget = effect.stat;
	var statAmount = effect.amount

	if target == "self":
		targetId = currentPlayer;
	elif target == "other":
		targetId = (currentPlayer + 1) % 2;

	var hud = get_tree().get_root().find_node("HUD", true, false);

	if(targetId >= 0):
		players[targetId][statTarget] += int(statAmount);
		if statTarget == "frustration":
			hud.frustrationReceive(targetId+1, int(statAmount));
		if statTarget == "rage":
			hud.rageReceive(targetId+1, int(statAmount));
		if statTarget == "money":
			hud.moneyReceive(targetId+1, int(players[targetId].money + statAmount));
		if statTarget == "houseHp":
			hud.houseHPReceive(targetId+1, int(statAmount));

	else:
		if statTarget == "frustration":
			hud.frustrationReceive(1, int(statAmount));
			hud.frustrationReceive(2, int(statAmount));
		if statTarget == "rage":
			hud.rageReceive(1, int(statAmount));
			hud.rageReceive(2, int(statAmount));
		if statTarget == "money":
			hud.moneyReceive(1, int(players[0].money + statAmount));
			hud.moneyReceive(2, int(players[1].money + statAmount));
		if statTarget == "houseHp":
			hud.houseHPReceive(1, int(statAmount));
			hud.houseHPReceive(2, int(statAmount));
		players[0][statTarget] += int(statAmount);
		players[1][statTarget] += int(statAmount);

	if players[0].checkDed() != 0:
		endGame(0, players[0].checkDed());
		return;

	if players[1].checkDed() != 0:
		endGame(1, players[1].checkDed());
		return;

func instanciateStatus(status):
	var path = status.path;
	var statusInstance = load(str(baseDirStatus, path));
	var statusNode = statusInstance.instance();
	var target = status.target;
	var targetId = -1;

	if target == "self":
		targetId = currentPlayer;
	elif target == "other":
		targetId = (currentPlayer + 1) % 2;

	if(targetId >= 0):
		players[targetId].add_child(statusNode);
	else:
		players[0].add_child(statusNode);
		players[1].add_child(statusNode);

	statusNode.doSomething();
	pass

func instanciateResponses(responseName):
	var path = "res://Scenes/responses/response.tscn";
	var baseDir = "res://assets/Responses/incendieResponse.json";
	var responseInstance = load(path);
	var responseNode = responseInstance.instance();
	var file = File.new();
	file.open(baseDir, file.READ);
	var text = file.get_as_text();
	var pool_event = JSON.parse(text);

	print(" = ", responseName);

	for i in pool_event.result:
		if i.name == responseName:
			responseNode.init(i);
	hcontainer.add_child(responseNode);
	pass

func instanciateStatusBars():
	var hud = get_tree().get_root().find_node("HUD", true, false);

	for i in players.size():
		hud.initBars(i + 1, players[i].frustration, players[i].money)

func get_first_player_class():
	return players[0].className;

func get_second_player_class():
	return players[1].className;
