@tool

extends Area2D
class_name Card
var compatible_sticky_notes: Array[StickyNote] = []
var own_sticky_notes: Array[StickyNote] = []
var current_sticky_note: StickyNote = null
var wiggle_pos: float = 0
var wiggle_intensity: float = 0
var noise: Noise = FastNoiseLite.new()
var wiggle_tween
var scale_tween

var transfor_arr: Array[Transform2D] = [
	Transform2D(0.9, Vector2(-125, -83)),
	Transform2D(-0.3, Vector2(-126, -75)),
	Transform2D(-0.3, Vector2(-126, -74)),
	Transform2D(-0.3, Vector2(-126, -73)),
	Transform2D(0.5, Vector2(-126, -77))
]

@export var text: String = "" :
	set(value):
		text = value
		if get_children() != [] or Engine.is_editor_hint():
			$Label.text = value
			var curr_frame = text.hash() % $BackgroundSprite.sprite_frames.get_frame_count($BackgroundSprite.animation)
			$BackgroundSprite.frame = text.hash() % $BackgroundSprite.sprite_frames.get_frame_count($BackgroundSprite.animation)
			$Label.rotation = deg_to_rad(transfor_arr[curr_frame].get_rotation())
			$Label.position = transfor_arr[curr_frame].origin
		if !Engine.is_editor_hint():
			wiggle_pos = float(text.hash() % 100)
			_handle_wiggle(0)
@export var wiggle_strength: float = 0.2
@export var wiggle_speed: float = 5
@export_range(1, 2) var scale_bump: float = 1.05
@export_range(1.0, 10.0) var bounce_speed: float = 5
@export var highlighted: bool = false:
	set(highlight):
		if highlight != highlighted:
			highlighted = highlight

			if is_inside_tree() and is_node_ready():
				if scale_tween: scale_tween.kill()
				if wiggle_tween: wiggle_tween.kill()
				if highlighted:
					scale_tween = get_tree().create_tween()
					scale_tween.tween_property(self, "scale", Vector2(scale_bump, scale_bump), 0.1)
					wiggle_tween = get_tree().create_tween()
					wiggle_tween.tween_property(self, "wiggle_intensity", 1, 0.2)
				else:
					scale_tween = get_tree().create_tween()
					scale_tween.tween_property(self, "scale", Vector2(1, 1), 0.3)
					wiggle_tween = get_tree().create_tween()
					wiggle_tween.tween_property(self, "wiggle_intensity", 0, 0.5)
			else:
				if highlighted:
					scale = Vector2(scale_bump, scale_bump)
					wiggle_intensity = 1
				else:
					scale = Vector2(1,1)
					wiggle_intensity = 0
					
@export var voice_line: AudioStream = null
@export var is_dragable: bool = false
@onready var diameter = $CollisionShape2D.shape.height
@onready var sticky_note_anchor: Node2D = $"sticky note anchor"

var is_dragged: bool = false:
	set(dragged):
		is_dragged = dragged
		z_index = int(dragged)

var is_mouse_entered: bool = false
var mouse_offset: Vector2

func _ready():
	
	_handle_wiggle(0)
	if not Engine.is_editor_hint() and is_inside_tree():
		for sticky_note in self.get_children():
			if sticky_note is StickyNote: self.own_sticky_notes.append(sticky_note as StickyNote)
		
		for sticky_note in get_tree().get_nodes_in_group(name):
			if sticky_note is StickyNote: self.compatible_sticky_notes.append(sticky_note as StickyNote)
	
		compatible_sticky_notes.append_array(own_sticky_notes)
		
		if own_sticky_notes.size() == 2:
			own_sticky_notes[0].sibling = own_sticky_notes[1]
			own_sticky_notes[1].sibling = own_sticky_notes[0]
		
	$BackgroundSprite.frame = text.hash() % $BackgroundSprite.sprite_frames.get_frame_count($BackgroundSprite.animation)
	$Label.text = self.text
	
	$Label.theme = State.current_main_theme
	State.theme_changed.connect(func change_theme(new_theme): $Label.theme = new_theme)
	
	wiggle_pos = float(text.hash() % 100)
	if not Engine.is_editor_hint():
		_handle_wiggle(0)

func _process(delta: float) -> void:
	if highlighted:
		_handle_wiggle(delta)
	
	if get_overlapping_areas().size() > 0 and is_dragable:
		for area in get_overlapping_areas():
			if area is Card or area is CardCollider:
				if area is CardCollider:
					position += area.direction * delta
				elif not (area.highlighted or self.highlighted) and area.is_dragable: 
					var diff:Vector2 = position - area.position
					position -= diff.normalized() * ((diff.length()-diameter)/diameter) * bounce_speed * (delta/(1.0/60))
	
	_move_card()

func get_text() -> String:
	return $Label.text

func _handle_wiggle(delta):
	wiggle_pos += delta * wiggle_speed * wiggle_intensity
	
	rotation = noise.get_noise_1d(wiggle_pos)*wiggle_strength

## Deprecated
func replace_with(card: Card):
	self.text = card.text
	self.compatible_sticky_notes = card.compatible_sticky_notes
	self.own_sticky_notes = card.own_sticky_notes
	self.voice_line = card.voice_line
	self.name = card.name
	
func _on_focus_entered():
	print(self, "is focused")

func _on_focus_exited():
	print(self, "is not focused")

func _on_mouse_entered():
	is_mouse_entered = true
	if not Input.is_action_pressed("mouse_left"):
		# Do nothing if mouse hovers over sticky_note
		if has_sticky_note_attached():
			if get_child(-1).highlighted:
				return
		highlighted = true
		if "handle_hover" in owner:
			owner.handle_hover(self)

func _on_mouse_exited():
	highlighted = false
	is_mouse_entered = false

func _on_input_event(viewport, event, shape_idx):
	
	if event is InputEventMouseMotion:
		_move_card()
		
	if event is InputEventMouseButton:
		if event.button_index == MOUSE_BUTTON_LEFT:
			if "handle_mouse_button" in owner:
				mouse_offset = (get_viewport().get_mouse_position() - position)                
				if highlighted:
					owner.handle_mouse_button(self, event)

func _move_card():
	if is_dragged:
		position += (get_viewport().get_mouse_position() - position) - mouse_offset

func has_sticky_note_attached() -> bool:
	return get_child(-1) is StickyNote

func get_attached_sticky_note() -> StickyNote:
	return null if not has_sticky_note_attached() else get_child(-1)

func preview_sticky_note(sticky_note: StickyNote):
	sticky_note.reparent(self.get_parent())
	sticky_note.owner = owner
	sticky_note.tween_transform_to(Transform2D(0, sticky_note_anchor.global_position + 0 * Vector2(sticky_note.diameter, sticky_note.diameter)))

func attach_sticky_note(sticky_note: StickyNote) -> bool:
	if has_sticky_note_attached():
		return false
	sticky_note.reparent(self)
	sticky_note.owner = self.owner
	sticky_note.position = sticky_note_anchor.position
	sticky_note.on_board = false
	current_sticky_note = sticky_note
	sticky_note.attached_to = self
	return true

func remove_sticky_note() -> StickyNote:
	if not is_instance_valid(current_sticky_note): return null
	var former_child:StickyNote = current_sticky_note
	current_sticky_note = null
	former_child.reparent(get_parent())
	former_child.owner = self.owner
	former_child.on_board = true
	former_child.attached_to = null
	return former_child

func exchange_sticky_note_with(new_note: StickyNote) -> StickyNote:
	var tmp = remove_sticky_note()
	attach_sticky_note(new_note)
	return tmp

## TODO why does this exist?    
func check_hover():
	if is_mouse_entered:
		_on_mouse_entered()

func reclaim_sticky_note():
	current_sticky_note.on_board = false
	current_sticky_note.tween_transform_to(sticky_note_anchor.global_transform)
	await current_sticky_note.transform_tween_finished
	current_sticky_note.reparent(self)
	current_sticky_note.owner = self.owner
