extends Node

signal bullet_shoot
signal bullet_selected(object)
signal state_changed

enum  GameState { PLAYER1_GUN_LOAD, PLAYER2_GUN_LOAD, GUN_ANIMATION, PLAYER1_UNLOAD,PLAYER2_UNLOAD}
enum PlayerChoice {SHOOT_SELF, SHOOT_OPPONENT}

var player_phase2_choice
var current_state = GameState.PLAYER1_GUN_LOAD
var bullets: Array

var player1_revolver: Node3D
var player2_revolver: Node3D
var is_player1_loaded: bool = false
var is_player2_loaded: bool = false
var bullet_stack: Node3D

var animPl: AnimationPlayer
func _ready() -> void:
	bullet_shoot.connect(on_bullet_shoot)
	bullet_selected.connect(on_bullet_selected)

func _input(event: InputEvent) -> void:
	if event.is_action_released("load"):
		set_player_turn()
	elif event.is_action_released("load2"):
		player1_revolver.load_bullet(bullet_stack.bullets[1])

func set_player_revolver(newRevolver):
	player1_revolver = newRevolver
func set_enemy_revolver(newRevolver):
	player2_revolver = newRevolver
func set_bullet_stack(newStack):
	bullet_stack = newStack

func add_bullet(bullet):
	bullets.append(bullet)


func on_bullet_selected(bullet_object: Node3D):
	if current_state == GameState.PLAYER1_GUN_LOAD:
		if bullet_object.is_loaded != true:
			set_state(GameState.GUN_ANIMATION)
			player1_revolver.load_bullet(bullet_object)

func set_state(newState):
	current_state = newState
	state_changed.emit()

func check_unloaded_bullets():
	var unloaded_bullets = Array()
	for bullet in bullets:
		if bullet.is_loaded != true:
			unloaded_bullets.append(bullet)
	if unloaded_bullets.size() > 0:
		return true
	else: 
		return false
		
func check_loaded_bullets(revolver: Node3D):
	if revolver.can_be_loaded():
		return true
	else:
		return false
	
func end_player_turn():
	if !is_player2_loaded:
		set_state(GameState.PLAYER2_GUN_LOAD)
	animPl.play("player_revolver_down")
	end_turn()
	
func end_enemy_turn():
	if is_player1_loaded == false:
		print("Player Turn")
		set_player_turn()
	end_turn()
func end_turn():
	if check_unloaded_bullets():
		if is_player1_loaded and is_player2_loaded:
			print("Phase 2")
			get_phase2_player_start()		
	else:
		set_state(GameState.PLAYER2_UNLOAD)
func get_enemy_revolver() -> Node3D:
	return player2_revolver
	
	
func get_phase2_player_start():
	var randNumb = randi_range(0,1)
	if randNumb == 0:
		set_state(GameState.PLAYER1_UNLOAD)
	else:
		set_state(GameState.PLAYER2_UNLOAD)


func on_bullet_shoot(target):
	pass


func set_player_turn():
	animPl.play("player_revolver_up")
func on_animation_finished(anim_name):
	if anim_name == "player_revolver_up":
		set_state(GameState.PLAYER1_GUN_LOAD)	
	elif anim_name == "player_revolver_down":
		set_state(GameState.PLAYER2_GUN_LOAD)
