extends KinematicBody2D

const MAX_SPEED = 600
const ACCELERATION = 1800
const FRICTION = 2000
var SPEED_FACTORS = []
var ACCELERATION_FACTORS = []
var FRICTION_FACTORS = []
var SCALE_FACTORS = []
var ALPHA_FACTORS = []

var empty_coroutine_frames = 0

var current_speed = MAX_SPEED
var current_acceleration = ACCELERATION
var current_friction = FRICTION

var MAX_LIFE = 30
const PICKUP_BONUS = 5
export var rota_speed = 100
export var slow_cooldown = 5
export var fast_cooldown = 5

var slow_cooldown_elapsed = 5
var fast_cooldown_elapsed = 5

var pathFollows = []

var vel = Vector2.ZERO
var last_dir = Vector2.ZERO
var curLife = MAX_LIFE

var coroutines = []

enum EInput{
	UP,
	RIGHT,
	DOWN,
	LEFT
}

const baseInputs = ["ui_up", "ui_right", "ui_down", "ui_left"]
var inputs = ["ui_up", "ui_right", "ui_down", "ui_left"]

onready var animationPlayer = $AnimationPlayer
onready var animationTree = $AnimationTree
onready var animationState = animationTree.get("parameters/playback")
onready var audioPlayer = $AudioPlayer
onready var sprite = $Sprite
onready var coll = $CollisionShape2D
onready var conf = $ConfusionStars
onready var pati = $Patins

var streams = []

var healthBar = null

func _ready():
	coroutines = []		
	pathFollows.append(get_node("ConfusionStars/Path2D/PathFollow2D"))
	pathFollows.append(get_node("ConfusionStars/Path2D/PathFollow2D2"))
	pathFollows.append(get_node("Patins/Path2D/PathFollow2D"))
	pathFollows.append(get_node("Patins/Path2D/PathFollow2D2"))
	if self.name == "Player1":
		healthBar = get_tree().get_nodes_in_group("healthbar")[0]
	elif self.name == "Player2":
		healthBar = get_tree().get_nodes_in_group("healthbar")[1]
	healthBar.maxHealthUpdated(MAX_LIFE)
	streams.append(load("res://Sounds/PaintJamPickupSound.wav"))
	streams.append(load("res://Sounds/PaintJamPaintAction.wav"))

func launch_slow():
	audioPlayer.stream = streams[1]
	audioPlayer.play()
	if slow_cooldown_elapsed < slow_cooldown:
		return
	curLife -= 3	
	slow_cooldown_elapsed = 0
	var world = get_parent()
	var inst = load("res://Scene/SlowTrail.tscn").instance()
	var dir = get_dir()	
	if dir == Vector2.ZERO:
		dir = (last_dir if last_dir != Vector2.ZERO else Vector2.DOWN)
	var angle = acos(dir.dot(Vector2.RIGHT))
	var modifier = 0
	if dir.y < 0:
		modifier += angle * -2
	inst.transform = inst.transform.rotated(angle + modifier)
	inst.position = self.position
	inst.slowFactor = 2
	world.add_child(inst)
	
func launch_fast():
	audioPlayer.stream = streams[1]
	audioPlayer.play()
	if fast_cooldown_elapsed < fast_cooldown:
		return
	curLife -= 3
	fast_cooldown_elapsed = 0
	var world = get_parent()
	var inst = load("res://Scene/FastTrail.tscn").instance()
	var dir = get_dir()	
	if dir == Vector2.ZERO:
		dir = (last_dir if last_dir != Vector2.ZERO else Vector2.DOWN)
	var angle = acos(dir.dot(Vector2.RIGHT))
	var modifier = 0
	if dir.y < 0:
		modifier += angle * -2
	inst.transform = inst.transform.rotated(angle + modifier)
	inst.position = self.position
	inst.fastFactor = 2
	world.add_child(inst)

func _process(delta):
	for each in pathFollows:
		each.set_offset(each.get_offset() + delta * rota_speed)
	
	if (self.name == "Player1" && Input.get_action_strength("gameplay_slow") > 0) \
	   || (self.name == "Player2" && Input.get_action_strength("gameplay_slow2") > 0):
		launch_slow()
		
	if (self.name == "Player1" && Input.get_action_strength("gameplay_fast") > 0) \
	   || (self.name == "Player2" && Input.get_action_strength("gameplay_fast2") > 0):
		launch_fast()
	
	updatePaintEffects(delta)
	curLife -= delta
	slow_cooldown_elapsed += delta
	fast_cooldown_elapsed += delta
	if curLife <= 0:
		get_node("/root/World/GameManager").endGame()
	healthBar.healthUpdated(curLife)		

func get_dir():
	var input_vector = Vector2.ZERO
	
	if self.name == "Player1":
		input_vector.x = Input.get_action_strength(inputs[EInput.RIGHT]) - Input.get_action_strength(inputs[EInput.LEFT])
		input_vector.y = Input.get_action_strength(inputs[EInput.DOWN]) - Input.get_action_strength(inputs[EInput.UP])
	elif self.name == "Player2":
		input_vector.x = Input.get_action_strength(inputs[EInput.RIGHT] + "2") - Input.get_action_strength(inputs[EInput.LEFT] + "2")
		input_vector.y = Input.get_action_strength(inputs[EInput.DOWN] + "2") - Input.get_action_strength(inputs[EInput.UP] + "2")
	
	input_vector = input_vector.normalized()
	return input_vector

func setScale(scale):
	sprite.scale = scale;
	coll.scale = scale;
	conf.scale = scale;

func setAlpha(alpha):
	sprite.self_modulate = Color(1,1,1, alpha)

func array_mul(array):
	var val = 1
	for i in array:
		val *= i
	return val

func array_sum(array):	
	var val = 0
	for i in array:
		val += i
	return val

func array_specsum(array):	
	if array.size() == 0:
		return 1
	var smaller = []
	var bigger = []
	for val in array:
		smaller.append(val) if val < 1 else bigger.append(val)
	smaller = array_mul(smaller)
	bigger = 1 if bigger.size() == 0 else array_sum(bigger)
	return smaller * bigger

func update_current():
	current_speed = MAX_SPEED * array_specsum(SPEED_FACTORS)
	current_acceleration = ACCELERATION * array_specsum(ACCELERATION_FACTORS)
	current_friction = FRICTION * array_specsum(FRICTION_FACTORS)
	setScale(Vector2.ONE * array_specsum(SCALE_FACTORS))
	if SCALE_FACTORS.size() > 1:
		print("FACTO == " + String(SCALE_FACTORS))
		print("SCALE == " + String(Vector2.ONE * array_specsum(SCALE_FACTORS)))
	setAlpha(1 * array_specsum(ALPHA_FACTORS))

func _physics_process(delta):
	var input_vector = get_dir()
	
	update_current()
	
	if input_vector != Vector2.ZERO:
		last_dir = input_vector
		animationTree.set("parameters/Idle/blend_position", input_vector)
		animationTree.set("parameters/Run/blend_position", input_vector)
		animationState.travel("Run")
		vel = vel.move_toward(input_vector * current_speed, current_acceleration * delta)
	else:
		animationState.travel("Idle")
		vel = vel.move_toward(Vector2.ZERO, current_friction * delta)
	
	vel = move_and_slide(vel)

func updatePaintEffects(delta):	
	var updated = []
	#if coroutines.size() == 0:
	#	empty_coroutine_frames += 1
	#else:
	#	empty_coroutine_frames = 0
	
	#if empty_coroutine_frames > 2 || coroutines.size() > 0:
	ACCELERATION_FACTORS = []
	FRICTION_FACTORS = []
	SPEED_FACTORS = []
	SCALE_FACTORS = []
	ALPHA_FACTORS = []
	for rout in coroutines:
		if rout != null && rout.is_valid():			
			updated.append(rout.resume(delta))
			
	coroutines = updated + []

func addCoroutine(routine):
	audioPlayer.stream = streams[0]
	audioPlayer.play()
	curLife = MAX_LIFE if (curLife + PICKUP_BONUS > MAX_LIFE) else curLife + PICKUP_BONUS
	coroutines.append(routine)
