class_name Numpad extends Node2D

var numpad_buffer = Array()
var proposed_ask: int
signal ask_proposed(amount)

#var turn_manager: TurnManager
var audience_manager: AudienceManager
var game_manager: GameManager
var turn_manager: TurnManager

@export var progress_bar: ProgressBar
@export var reminder_timer: Timer
@export var error_audio_player: AudioStreamPlayer2D
@export var success_audio_player: AudioStreamPlayer2D

func _ready() -> void:
	progress_bar.max_value = reminder_timer.wait_time
	

func _process(delta: float) -> void:
	progress_bar.value = reminder_timer.time_left

# number entry function called by numbered button children
func keypad_entry(entry: int):
	numpad_buffer.append(str(entry))

func keypad_backspace():
	if numpad_buffer.size() > 0:
		numpad_buffer.remove_at(-1)

func keypad_submit():
	var keypad_output: String = "".join(numpad_buffer)
	proposed_ask = int(keypad_output) * 1000
	
	if proposed_ask == 0: return
	
	match game_manager.state:
		game_manager.bidding_state.READY:
			if proposed_ask == game_manager.starting_price:
				game_manager.state = game_manager.bidding_state.ASKING
				success_audio_player.play()
				ask_proposed.emit(proposed_ask)
				print("starting the bidding at $" + str(proposed_ask))
				reminder_timer.start(-1)
			else:
				error_audio_player.play()
		game_manager.bidding_state.ASKING:
			if proposed_ask == game_manager.starting_price or proposed_ask == game_manager.current_bid or proposed_ask == audience_manager.current_ask and proposed_ask != 0:
				success_audio_player.play()
				ask_proposed.emit(proposed_ask)
				print("asking for $" + str(proposed_ask))
				reminder_timer.start(-1)
			else:
				error_audio_player.play()
		game_manager.bidding_state.BID:
			if proposed_ask > game_manager.current_bid:
				game_manager.state = game_manager.bidding_state.ASKING
				success_audio_player.play()
				ask_proposed.emit(proposed_ask)
				print("asking for $" + str(proposed_ask))
				reminder_timer.start(-1)
			else:
				error_audio_player.play()
		_:
			error_audio_player.play()
	
	# need to avoid starting the reminder timer before
	# the auction starts
	numpad_buffer.clear()
