extends CharacterBody3D

const SPEED = 3.5
const JUMP_VELOCITY = 3.5

var walk_animation_time = 0
var face_rotation = 0
var face_left = false

var combatable = true

var iframes = 0
var knockback_time = 0
var health = 100

var combo_hits = 0
var combo_timer = 0
var swing_timer = 0

var queue_swing = false

var current_weapon = "test_sword"

@onready var game = get_parent()
@onready var camera = game.get_node("PlayerCamera")

func hit_me():
	iframes = 0.5
	health -= 10
	
func get_my_weapon_info(value: String):
	return get_weapon_info(current_weapon, value)
	
func get_weapon_info(weapon: String, value: String):
	if value in Global.weapons[weapon]: 
		return Global.weapons[weapon][value]
	else: return null
	
func on_hit(hitter: Node3D = null) -> void:
	iframes = 0.8
	
	if hitter:
		knockback_time = 0.25
		velocity += hitter.global_position.direction_to(global_position) * 8
		velocity.y = 0

func _ready() -> void:
	LimboConsole.register_command(hit_me)
	
func _process(delta: float) -> void:
	
	if iframes > 0:
		iframes -= delta
		$DreamerBody/Body.modulate.a = 0.5
	else:
		$DreamerBody/Body.modulate.a = 1
		
	if knockback_time > 0:
		knockback_time -= delta

func _physics_process(delta: float) -> void:
	$DreamerBody.look_at(game.get_node("PlayerCamera").global_position)
	$DreamerBody.rotation.x = 0
	face_rotation = $DreamerBody.rotation.y
	if not face_rotation: face_rotation = 0
	
	if not is_on_floor():
		velocity += get_gravity() * delta
		
	var viewport_half = (get_viewport().get_visible_rect().size / 2.0)
	var player_position = camera.unproject_position(global_transform.origin)
	
	if face_left:
		$DreamerBody.rotation.y = face_rotation + deg_to_rad(180)
		$DreamerBody/Animator.set("parameters/layering/blend_amount", 1.0)
	else:
		$DreamerBody.rotation.y = face_rotation
		$DreamerBody/Animator.set("parameters/layering/blend_amount", 0.0)
		
	var mouse_point_angle = player_position.angle_to_point(get_viewport().get_mouse_position())
	
	if combatable:
		$HitCollision.rotation.y = -mouse_point_angle + face_rotation
		
		if abs(rad_to_deg(mouse_point_angle) - (-90)) < 50:
			$HitCollision/Shape.shape.size.x = 1.5
		else:
			$HitCollision/Shape.shape.size.x = 1.2
		
		if (rad_to_deg(mouse_point_angle) < -90) or (rad_to_deg(mouse_point_angle) > 90):
			face_left = true
			
			var mouse_pos = get_viewport().get_mouse_position()
			mouse_pos.y = (viewport_half.y) + ((viewport_half.y) - mouse_pos.y)
			
			#$DreamerBody/Body/ArmPivot.rotation.z = viewport_half.angle_to_point(mouse_pos)
		else:
			face_left = false
			$DreamerBody/Body/ArmPivot.scale.y = 1
			$DreamerBody/Body/ArmPivot.scale.x = 1
			
		$DreamerBody/Animator.set("parameters/hold_weapon/blend_amount", 1.0)
	else:
		$DreamerBody/Body/ArmPivot.global_rotation.y = face_rotation
		$DreamerBody/Body/ArmPivot.scale.y = 1
		$DreamerBody/Body/ArmPivot.scale.x = 1
		$DreamerBody/Body/ArmPivot.rotation.z = 0
			
		$DreamerBody/Animator.set("parameters/hold_weapon/blend_amount", 0.0)
	
	if Input.is_action_pressed("jump") and is_on_floor():
		velocity.y = JUMP_VELOCITY
		$DreamerBody/Animator.set("parameters/jump/request", AnimationNodeOneShot.ONE_SHOT_REQUEST_FIRE)

	var input_dir := Input.get_vector("move_left", "move_right", "move_up", "move_down")
	if not combatable:
		if input_dir.x > 0:
			face_left = false
		if input_dir.x < 0:
			face_left = true
			
	if swing_timer > 0: swing_timer -= delta
	if combo_timer > 0:
		combo_timer -= delta
		if combo_timer <= 0:
			combo_hits = 0
		
	if Input.is_action_just_pressed("attack") or queue_swing:
		if swing_timer > 0:
			if swing_timer < 0.1:
				queue_swing = true
		else:
			queue_swing = false
			
			swing_timer = get_my_weapon_info("swing_time")
			combo_timer = get_my_weapon_info("combo_timeout")
			if swing_timer == null: swing_timer = 0.0
			if combo_timer == null: combo_timer = 0.0
			
			combo_hits += 1
			
			var slash = load("res://scenes/effects/slash.tscn").instantiate()
			game.add_child(slash)
			slash.global_position = global_position
			slash.global_rotation.y = $HitCollision.global_rotation.y + deg_to_rad(180)
			slash.play_effect()
			
			$DreamerBody/Animator.set("parameters/swing_weapon/request", AnimationNodeOneShot.ONE_SHOT_REQUEST_FIRE)
			
			var hits = $HitCollision.get_overlapping_bodies()
			
			var knockback = 0
			var damage = 0
			
			if get_my_weapon_info("combo_weapon"):
				if combo_hits < get_my_weapon_info("hits_to_finish"):
					damage = get_my_weapon_info("damage_mid_combo")
					knockback = get_my_weapon_info("knockback_mid_combo")
				else:
					damage = get_my_weapon_info("damage")
					knockback = get_my_weapon_info("knockback")
					
					combo_hits = 0
					
					swing_timer = get_my_weapon_info("swing_time_combo_finish")
					if swing_timer == null: swing_timer = 0.0
			else:
				damage = get_my_weapon_info("damage")
				knockback = get_my_weapon_info("knockback")
				
				combo_hits = 0
			
			for body in hits:
				if body == self: continue
				
				if "health" in body:
					body.health -= damage
					
					var knockback_pos = global_position
					knockback_pos.y = 0
					var knockback_body_pos = body.global_position
					knockback_body_pos.y = 0
					
					body.position.y += 0.2
					body.velocity.y = 0.4
					body.velocity += knockback_pos.direction_to(knockback_body_pos) * knockback
					
					if body.velocity.length() > knockback:
						body.velocity = body.velocity.normalized() * knockback
						
					if "mid_knockback" in body:
						body.mid_knockback = true
						
					if "on_knockback" in body:
						body.on_knockback()
						
					var damage_text = preload("res://scenes/effects/damage_text.tscn").instantiate()
					game.add_child(damage_text)
					damage_text.global_position = body.global_position
					damage_text.get_node("Label").text = str(floor(damage))
	
	var direction = (camera.transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
	if direction and (knockback_time <= 0):
		velocity.x = direction.x * SPEED
		velocity.z = direction.z * SPEED
		
		$DreamerBody/Animator.set("parameters/walk/blend_amount", abs(direction.length()))
	else:
		
		velocity.x = move_toward(velocity.x, 0, delta * 24)
		velocity.z = move_toward(velocity.z, 0, delta * 24)
		
		$DreamerBody/Animator.set("parameters/walk/blend_amount", 0)
		
	if direction and is_on_floor():
		walk_animation_time += delta * 25
		
		$DreamerBody.position.y = sin(walk_animation_time + 1) / 16
		$DreamerBody.rotation.z = sin(walk_animation_time / 2) / 16
	else:
		walk_animation_time = 0
		
		$DreamerBody.rotation.z /= 1 + (delta * 2.5)
		
		$DreamerBody.position.y /= 1 + (delta * 12)
		
	if is_on_floor():
		$DreamerBody/Animator.set("parameters/fall/blend_amount", 0)
		$DreamerBody/Animator.set("parameters/leap/blend_amount", 0)
	else:
		if velocity.y < 0:
			$DreamerBody/Animator.set("parameters/fall/blend_amount", 1)
			$DreamerBody/Animator.set("parameters/leap/blend_amount", 0)
		else:
			$DreamerBody/Animator.set("parameters/fall/blend_amount", 0)
			$DreamerBody/Animator.set("parameters/leap/blend_amount", 1)

	move_and_slide() 
	
		
	$Shadow.global_position.y = $Floorcast.get_collision_point().y + 0.01
	
