extends Node2D

@onready var card_manager = $CardManager
@onready var deck = $CardManager/deck
@onready var player_1_hand = $CardManager/Player1Hand
@onready var player_2_hand = $CardManager/Player2Hand
@onready var player_3_hand = $CardManager/Player3Hand
@onready var player_4_hand = $CardManager/Player4Hand

signal dealt

func _ready():
	setup_game()

func setup_game():
	# Create a deck of cards
	create_standard_deck()
	deck._held_cards.shuffle()
	
	# Deal initial hand
	var deal_r: int =1
	while true:
		deal_cards_to_hand(3, player_1_hand)
		deal_cards_to_hand(3, player_2_hand)
		deal_cards_to_hand(3, player_3_hand)
		deal_cards_to_hand(3, player_4_hand)
		if deal_r == 3:
			dealt.emit()
			break
		else:
			await Timer.new()
			deal_r += 1

func create_standard_deck():
	var suits = ["Club", "Diamond", "Heart", "Spade"]
	var values = ["A", "6", "7", "8", "9", "10", "B", "Q", "K"]
	
	for suit in suits:
		for value in values:
			var card_name = "%s_%s" % [suit, value]
			var card = card_manager.card_factory.create_card(card_name, deck)
			deck.add_card(card)

func deal_cards_to_hand(count: int, player):
	for i in count:
		if deck.get_card_count() > 0:
			var card = deck.get_top_cards(1).front()
			player.move_cards([card])
