extends Node

class_name WeaponSystem

@export var default_pistol: WeaponSubStateMachine
@export var default_knife: WeaponSubStateMachine

@export var animation_player: AnimationPlayer
@export var camera: PlayerCamera

var current_state: WeaponSubStateMachine

var slots: Dictionary[StringName,WeaponSubStateMachine] = {
	"primary": null,
	"secondary": default_pistol,
	"knife": default_knife,
	"bomb": null,
	"ability_first": null,
	"ability_second": null,
	"ability_third": null,
	"ultimate": null
}

signal switched_to(state: WeaponSubStateMachine)

func _ready() -> void:
	for child in get_children():
		if child is WeaponSubStateMachine:
			child.system = self
			child.animation_player = animation_player
			child.player_camera = camera
		else:
			push_warning("Child of weapon system is not ability or weapon")
	
	current_state = default_pistol
	slots["knife"] = default_knife
	slots["secondary"] = default_pistol
	current_state.enter()

func can_add(slot: StringName) -> bool:
	return slots.has(slot)

func add(state: WeaponSubStateMachine, slot: StringName) -> void:
	if can_add(slot) == false:
		return
	
	add_child(state)
	
	slots[slot] = state
	state.system = self
	state.animation_player = animation_player
	state.player_camera = camera


func switch(to: StringName):
	if slots.has(to) == false or slots[to] == null or slots[to] == current_state:
		return
	current_state.exit()
	current_state.in_use = false
	current_state = slots[to]
	current_state.enter()
	current_state.in_use = true
	
	switched_to.emit(current_state)
	
	#update_remotes.rpc(to)

@rpc("authority","call_remote","reliable")
func update_remotes(to: StringName):
	switch(to)

func _process(delta: float) -> void:
	if current_state == null:
		push_error("State is not set")
		return
	current_state.update(delta)

func _physics_process(delta: float) -> void:
	if current_state == null:
		push_error("State is not set")
		return
	current_state.physics_update(delta)

func _input(event: InputEvent) -> void:
	if is_multiplayer_authority() == false: return
	
	if event.is_action_pressed("plr_ult"):
		switch("ultimate")
	elif event.is_action_pressed("plr_bomb"):
		switch("bomb")
	elif event.is_action_pressed("plr_primary"):
		switch("primary")
	elif event.is_action_pressed("plr_active_first"):
		switch("ability_first")
	elif event.is_action_pressed("plr_active_second"):
		switch("ability_second")
	elif event.is_action_pressed("plr_active_third"):
		switch("ability_third")
	elif event.is_action_pressed("plr_secondary"):
		switch("secondary")
	elif event.is_action_pressed("plr_knife"):
		switch("knife")
	
	if event.is_action_pressed("plr_fire"):
		current_state.use_begin.rpc()
	if event.is_action_released("plr_fire"):
		current_state.use_end.rpc()
	if event.is_action_pressed("plr_scope"):
		current_state.alternate_state()
	if event.is_action_pressed("plr_firemode"):
		current_state.switch_mode()
	
