extends Control

const dev_board_pre = preload("res://dev-util/board of devs.tscn")
var dev_board: Control

func _ready():
	dev_board = dev_board_pre.instantiate()

	if $cards.get_child_count(false) > 0:
		$cards.get_children(false)[0].grab_focus()

	# Testing code
	for item in dev_board.find_children("*"):
		if item is Card:
			spawn_card((item as Card).duplicate())
		elif item is StickyNote:
			spawn_sticky_note((item as StickyNote).duplicate())

func _process(delta: float):
	pass

func spawn_card(card: Card):
	$cards.add_child(card)

	if $cards.get_child_count(false) == 1:
		$cards.get_children(false)[0].grab_focus()

	populate_focus_neighbors()

func spawn_sticky_note(sticky_note: StickyNote):
	$sticky_notes.add_child(sticky_note)

	populate_focus_neighbors()

func populate_focus_neighbors():
	# TODO reorder cards based on position

	if $cards.get_child_count(false) <= 0:
		return

	var first_card = $cards.get_children(false)[0]
	var first_sticky_note = $sticky_notes.get_children(false)[0] if $sticky_notes.get_child_count(false) > 0 else first_card

	var first_board_card = $mindmap.get_children(false)[0] if $mindmap.get_child_count(false) > 0 else first_card

	var cards = $cards.get_children(false) as Array[Card]
	for i in cards.size():
		var card = cards[i]
		if card == first_card or not (card is Card):
			continue
		card.focus_neighbor_right = first_board_card # FIXME should be a valid focusable object, but it refuses
		card.focus_neighbor_left = first_sticky_note
		card.focus_neighbor_up = cards[(i - 1) % cards.size()]
		card.focus_neighbor_down = cards[(i + 1) % cards.size()]

	var sticky_notes = $sticky_notes.get_children(false) as Array[StickyNote]
	for i in sticky_notes.size():
		var sticky_note = sticky_notes[i]
		if not (sticky_note is StickyNote):
			continue
		sticky_note.focus_neighbor_right = first_card
		sticky_note.focus_neighbor_left = first_board_card
		sticky_note.focus_neighbor_up = sticky_notes[(i - 1) % sticky_notes.size()]
		sticky_note.focus_neighbor_down = sticky_notes[(i + 1) % sticky_notes.size()]

	var board_items = $mindmap.get_children(false) as Array
	for i in board_items.size():
		var board_item = board_items[i]
		board_item.focus_neighbor_right = first_sticky_note
		board_item.focus_neighbor_left = first_card
		board_item.focus_neighbor_up = board_items[(i - 1) % board_items.size()]
		board_item.focus_neighbor_down = board_items[(i + 1) % board_items.size()]
