class_name CardPicker extends CenterContainer

#fixme INI is probably redundant.
enum {
	INI,
	CARDS,
	CARDS_SELECTED,
	TRANSITION,
	POSTS,
	POSTS_SELECTED,
	DONE
}

@onready var source_board:Control = $"board of devs"

var has_stage = false: 
	set(focus):
		if not focus == has_stage:
			if focus:
				process_mode = Node.PROCESS_MODE_INHERIT
				self.show()
				self.mouse_filter = Control.MOUSE_FILTER_PASS
			else:
				self.mouse_filter = Control.MOUSE_FILTER_IGNORE
				self.hide()
				process_mode = Node.PROCESS_MODE_DISABLED
		has_stage = focus
		
var _input_locked = true
var selection_state = INI:
	set(state):
		selection_state = state
		_input_locked = !(state == CARDS or state == POSTS)
		
		if state == CARDS_SELECTED:
			var tween = get_tree().create_tween()
			tween.tween_property($thought_prompt, "modulate", Color(1, 1, 1, 0), 0.5)
		elif state == DONE:
			reset()

var anim_players:Array[AnimationPlayer] = []
var curr_selection_id: int = -1:
	set(new_id):
		if selection_state == CARDS or selection_state == POSTS:
			if not curr_selection_id == -1: options[curr_selection_id].highlighted = false
			
			if new_id > options.size() -1: curr_selection_id = 0
			elif new_id < 0: curr_selection_id = options.size() - 1
			else: curr_selection_id = new_id
			
			options[curr_selection_id].highlighted = true
		else:
			curr_selection_id = new_id
			
		print(curr_selection_id)

var output:Array = []
var options:Array = []

signal cards_picked(Array)

# Called when the node enters the scene tree for the first time.
func _ready():
	reset()
	
func reset():
	output = []
	options = []
	anim_players = []
	var card_controls = $cards.get_children()
	for control in card_controls:
		options.append(control.get_child(1))
		anim_players.append(control.get_child(0))
	curr_selection_id = 0
	for player in anim_players: player.play("reveal")

func fill_card_slots(id: int):
	var new_cards = source_board.get_cards_by_scene_id(id)
	
	for i in range(new_cards.size()):
		$cards.get_child(i).remove_child($cards.get_child(i).get_child(1))
		var new_card = new_cards[i]
		new_card.reparent($cards.get_child(i), false)
		new_card.owner = self
		new_card.connect("mouse_entered", Callable(self, "get_highlight"))
		options.append(new_card)
		anim_players.append($cards.get_child(i).get_child(0))
	reset()

func fill_post_slots():
	var sticky_notes: Array[StickyNote] = []
	for card in output:
		sticky_notes.append_array(card.own_sticky_notes)
	
	sticky_notes.shuffle()
	options = []
	for ancor in $sticky_notes.get_children():
		ancor.remove_child(ancor.get_child(1))
	
	for i in range(sticky_notes.size()):
		options.append(sticky_notes[i])
		$sticky_notes.get_child(i).add_child(options[i], false)
		options[i].owner = self
	
func _input(event):
	#if event.is_action_pressed("ui_end"):
	#	fill_card_slots(3)
	#	selection_state = CARDS
	
	if has_stage:
		if !_input_locked:
			if event.is_action_pressed("ui_up") or event.is_action_pressed("ui_left") or event.is_action_pressed("ui_focus_next"):
				curr_selection_id -= 1
			elif event.is_action_pressed("ui_down") or event.is_action_pressed("ui_right") or event.is_action_pressed("ui_focus_prev"):
				curr_selection_id += 1
			if event.is_action_pressed("ui_accept"):
				pick(curr_selection_id)
		elif event.is_action_pressed("skip"):
			##fixme: using skip causes a lot of invalid state
			return
			if selection_state == CARDS_SELECTED:
				transition()
				show_posts()
			elif selection_state == POSTS_SELECTED:
				transition()
			elif selection_state == TRANSITION:
				show_posts()
	

func pick(id: int):
	print("PICK")
	if id == -1:
		curr_selection_id = 0
		return
	
	if selection_state == CARDS:
		selection_state = CARDS_SELECTED
	elif selection_state == POSTS:
		selection_state = POSTS_SELECTED
		
	anim_players[id].play("pick")
	var yield_to = anim_players[id].animation_finished
	output.append(options[id])
	
	options.remove_at(id)
	anim_players.remove_at(id)
	
	var sibling_id = -1
	if selection_state == POSTS_SELECTED:
		sibling_id = options.find(output.back().sibling)
		options.remove_at(sibling_id)
		anim_players[sibling_id].play("unshuffle")
		anim_players.remove_at(sibling_id)
		print("yeet sibling ", sibling_id)
	
	var winning_id 
	print(options[1].text)
	if !(options[1].text == "" and not id == 1):
		randomize()
		winning_id = randi() % options.size()
		
		print("Winning ID ", id)
		
	else:
		winning_id = 2 if id == 0 else 0
		Steam.setAchievement("FIGHT_BACK")
		Steam.storeStats()
	
	output.append(options.pop_at(winning_id))
	anim_players.pop_at(winning_id).play("shuffle")
	
	for anim in anim_players:
		anim.play("unshuffle")
	
	await yield_to
	transition()

func transition():
	if selection_state == CARDS_SELECTED:
		selection_state = TRANSITION
		options = []
		anim_players = []
		for control in $sticky_notes.get_children():
			options.append(control.get_child(1))
			anim_players.append(control.get_child(0))
			control.get_child(0).play("post")
		curr_selection_id = -1
		
		fill_post_slots()
		
		await anim_players[0].animation_finished
		show_posts()
	elif selection_state == POSTS_SELECTED:
		var out_str:Array[String] = []
		for card in output:
			out_str.append(card.name)
		cards_picked.emit(out_str)
		selection_state = DONE
		State.leave_stage(self)

func show_posts():
	selection_state = POSTS
	for player:AnimationPlayer in anim_players:
		player.play("reset")
	

func handle_hover(new_highlight):
	if not _input_locked:
		curr_selection_id = options.find(new_highlight)

func handle_mouse_button(new_selection: Node, button_event: InputEventMouseButton):
	if not _input_locked:
		if button_event.button_index == MOUSE_BUTTON_LEFT and button_event.pressed:
			pick(options.find(new_selection))

func scene_finished(id: int, repeat):
	print(name, id, repeat)
	if not repeat:
		Input.mouse_mode = Input.MOUSE_MODE_VISIBLE
		fill_card_slots(id)
		State.transition_stage_to(self, true)
		selection_state = CARDS

func play_scene(_id, _repeat):
	pass
