class_name Player
extends GirlMob

onready var lighting_text = $"../../UI/LightingTime"
onready var necklace_light = $"NecklaceLight"
onready var lightning_ray = $"LightningRay"
onready var camera = $"../Camera2D"
onready var outline_material: Material = preload("res://shader/outline_material.tres")
onready var music_player = $"../../MusicPlayer"
onready var label = $"../../UI/Caption"
onready var blockade = $"../NecklaceWall"
var recent_collider: BaseMob = null
var lighting_time: float = 10.0
var strike_time: bool = false
var last_checkpoint: Vector2
var just_restarted = 0
var necklace_on = false

var animated = false

onready var reloadable = $"../Reloadable"
var clone_of_reloadable

var int_tick = 0

func _ready():
	lightning = $"../Lightning"
	lives = 1
	last_checkpoint = get_position()
	frozen = false
	outside_the_building = true
	_add_time(0)
	camera.fix_camera()
	base_max_velocity = 50.0
	clone_of_reloadable = reloadable.duplicate()
	
#	necklace_on = true
#	go_inside()
	
func _input(event):
	if animated:
		if event.is_action_pressed("necklace"):
			blockade.queue_free()
			label.set_visible(false)
			necklace_on = true
			body.set_sprite_frames(preload("res://asset/body_necklace.tres"))
			$"../../UI/LightingTime".set_visible(true)
	else:
		if event is InputEventKey and event.pressed:
			if event.is_action_pressed("move_up"): # and not walking_down and not walking_up:
				jump_grace_timer.start()
			elif event.is_action_pressed("restart") and lives > 0:
				lives = -100000
			elif event.is_action_pressed("sprint"):
				pass
#				if base_max_velocity < 400:
#					base_max_velocity = 1000.0
#				else:
#					base_max_velocity = 100.0

func _physics_process(_delta):
	int_tick += 1
	if int_tick > 10:
		var rld = $"../Reloadable"
		if rld != null:
			var mobs = rld.get_children()
			var lowest_dist = 100000.0
			for mob in mobs:
				if !mob.frozen:
					lowest_dist = min(mob.position.distance_to(position), lowest_dist)
			if lowest_dist < 500:
				music_player.set_combat_intensity(1.0 - lowest_dist / 500.0)
			else:
				music_player.set_combat_intensity(0.0)
		int_tick = 0
	if just_restarted > 0:
		just_restarted -= 1
		if just_restarted == 0:
			var new_clone = clone_of_reloadable.duplicate()
			get_parent().add_child(new_clone)
			reloadable = new_clone
			
	music_player.set_rain_intensity(-position.distance_to(Vector2(0, 0)) / 105.0)

func _process(_delta):
	pass

func _add_time(delta):
	if !necklace_on:
		return
	
	var ratio: float = (10.0 - lighting_time) / 10.0
	
	lighting_time -= delta
	if lighting_time < 0.0:
		strike_time = true
		lighting_time = 10.0
	if lighting_time > 9.99:
		lighting_text.clear()
		lighting_text.push_color(Color(1, 1, 1, 1))
		lighting_text.add_text("9.99")
	elif lighting_time > 3.0:
		lighting_text.clear()
		lighting_text.push_color(Color(1, 1, 1, 1))
		lighting_text.add_text("%2.2f" % lighting_time)
	else:
		lighting_text.clear()
		lighting_text.push_color(Color(1, 0, 0, 1))
		lighting_text.add_text("%2.2f" % lighting_time)
	necklace_light.set_energy(ratio * 2.0)
	
	var color = outline_material.get_shader_param("color")
	outline_material.set_shader_param("color", Color(color.r, color.g, color.b, ratio / 1.0))

func read_input(delta):
	if animated:
		flip(true)
		velocity.x += speed
		return
		
	if Input.is_action_pressed("move_up"):
		velocity.y -= delta * gravity * jump_strength
	
	if Input.is_action_pressed("move_right"):
		velocity.x += speed
		flip(true)
	elif Input.is_action_pressed("move_left"):
		velocity.x -= speed
		flip(false)
	else:
		velocity.x += speed * -sign(velocity.x)
	
	if abs(velocity.x) < 0.01 and abs(velocity.y) < 0.01 and Input.is_action_pressed("fast_forward"):
		_add_time(delta * 3)

func finalize(delta):
	if (abs(real_velocity.x) > 0.05 or abs(real_velocity.y) > 0.05 or walking_up) and lives > 0:
		camera.fix_camera()
		_add_time(delta)
	
	lightning_ray.set_cast_to(Vector2(200 if sprite_direction else -200, 0))
	var collider = lightning_ray.get_collider()
	if collider is BaseMob:
		if recent_collider != null && recent_collider != collider:
			recent_collider.body.set_material(null)
		collider.body.set_material(outline_material)
		recent_collider = collider
	else:
		if recent_collider != null and is_instance_valid(recent_collider):
			recent_collider.body.set_material(null)
		recent_collider = null
	
	if strike_time:
		strike_time = false
		if collider == null:
			strike()
			lightning.strike(position)
		else:
			collider.strike()
			lightning.strike(collider.position)
			if collider is Candle:
				last_checkpoint = collider.get_position() + collider.respawn_point.get_position()
	
func strike():
	.strike()
	lighting_text.set_visible(false)

func restart():
	lives = 1
	walker.stop_all()
	set_position(last_checkpoint)
	set_visible(true)
	camera.fix_camera()
	lighting_time = 10.0
	reloadable.queue_free()
	just_restarted = 2
	recent_collider = null
	flip(true)
	velocity = Vector2(0, 0)

func watch_for_death(delta):
	if lives < 1:
		if lives > -100000:
			if DEBUG:
				lives = 1
				lighting_time = 10.0
			else:
				set_scale(Vector2(1.0, get_scale().y - delta * 5.0))
				if get_scale().y < 0.0:
					set_visible(false)
				if lightning.landed == false and lightning.expanding == false:
					set_scale(Vector2(1.0, 1.0))
					_add_time(0)
					lighting_text.set_visible(true)
					restart()
		else:
			restart()

func _on_necklace_scene(_body):
	animated = true
	label.parse_bbcode('[center][color=#AAAAAA]' + '(press N to put on the necklace)' + '[/color][/center]')
	label.set_visible(true)

func _on_necklace_scene_end(_body):
	$"../../UI/Logo".set_visible(true)
	$Timer.start()

func go_inside():
	set_position(get_position() + Vector2(128.0, 0))
	$"../../UI/Logo".set_visible(false)
	base_max_velocity = 100.0
	camera.set_position(camera.get_position() - Vector2(96.0, 0.0) + Vector2(24.0, 0.0))
	last_checkpoint = get_position()
	outside_the_building = false
	music_player.go_inside()
	lighting_time = 10.0
	animated = false
	var fx = AudioServer.get_bus_effect(1, 0)
	fx.set_room_size(0.5)
	fx.set_wet(0.5)
