extends TextureRect

class_name Card

const PIXEL_PER_ROTATION: float = 32.
const ROTATION = PI/6.

@export var card_resource: CardResource
var dragged: bool = false

func _ready() -> void:
	$UnitPreview.texture = card_resource.preview
	texture = card_resource.background
	$CostBubble/Cost.text = str(card_resource.cost)
	$ExperimentalBadge.visible = card_resource.experimental
	$Name.text = tr(card_resource.name_key)
	$Description.text = tr(card_resource.description_key)

func _gui_input(event: InputEvent) -> void:
	if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
		dragged = true
		var pos = global_position
		top_level = true
		global_position = pos
		accept_event()

func _input(event: InputEvent) -> void:
	if dragged and event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT and not event.pressed:
		dragged = false
		
		var pos = global_position
		top_level = false
		global_position = pos
		accept_event()

func _process(_delta: float) -> void:
	if not dragged:
		rotation = lerp(rotation,0.,0.25)
		return
	
	var mouse_pos = get_global_mouse_position()-get_combined_pivot_offset()
	global_position = lerp(global_position,mouse_pos,0.25)
	var relative_x = mouse_pos.x - global_position.x
	rotation = lerp(rotation,clamp(relative_x/PIXEL_PER_ROTATION*ROTATION,-ROTATION,ROTATION),0.25)
