extends KinematicBody2D

var direction = Vector2(0,0)
var prevdirection = Vector2(0,0)
var speed = 7.5

var monet = 0

var check = false

var time = 0

export var beers = [0, 5, 5, 5]
var inventory = [0,0,0]
export var taps = [false, false, false, false]
var keys = [false,false,false,false, false]
var textures = [null, preload("res://Drank1.tres"), preload("res://Drank2.tres"), preload("res://Drank3.tres")]

func restock():
	if monet >= 40:
		monet -= 40
		for i in range(4):
			beers[i] += 1
		get_node("Camera2D").get_node("UI").get_node("HBoxContainer").get_node("Label").update()

func inventory_change(item, slot):
	get_node("Camera2D").get_node("UI").get_node("HSplitContainer").get_children()[slot].texture = textures[item]

func checkdir():
	if !keys.count(true): 
		if prevdirection[1] >= 0: get_node("Body").animation = "Front"
		else: get_node("Body").animation = "Back"
	elif direction.normalized()[1] == 1:
		get_node("Body").animation = "Forward"
	elif direction.normalized()[1] == -1:
		get_node("Body").animation = "Backward"
	elif direction[0] > 0 : get_node("Body").animation = "Right"
	elif direction[0] < 0 : get_node("Body").animation = "Left"

func vektorins(pressed, vector, key):
	prevdirection = direction
	if pressed && !keys[key]:
		direction -= vector
		keys[key] = true
	elif !pressed: 
		direction += vector
		keys[key] = false
	checkdir()
	pass

func fill(event):
	if !keys[4] && event.pressed:
		for i in range(4):
			if taps[i] && (beers[i] > 0) && inventory.has(0):
				beers[i] -= 1
				for slot in range(3):
					if inventory[slot] == 0: 
						print("Pouring: " + str(i) + " in slot " + str(slot) + " in place of " + str(inventory[slot]))
						inventory[slot] = i
						inventory_change(i, slot)
						break
				print(inventory)
			else: print("Beer " + str(i) + " not available or inventory full " + str(!inventory.has(0)))
		keys[4] = true
	elif keys[4] && !event.pressed:
		keys[4] = false

func _ready():
	pass 

func _input(event):
	if event is InputEventKey:
		match(event.scancode):
			KEY_W: vektorins(event.pressed, Vector2(0,1), 0)
			KEY_S: vektorins(event.pressed, Vector2(0,-1), 1)
			KEY_D: vektorins(event.pressed, Vector2(-1,0), 2)
			KEY_A: vektorins(event.pressed, Vector2(1,0), 3)
			KEY_E: 
				get_tree().call_group("client", "take_drink")
				get_tree().call_group("phone", "make_call")
				fill(event)
			KEY_ESCAPE: get_tree().quit()

func _process(delta):
	
	move_and_collide(direction.normalized() * speed)
	if position[1] > 700 : z_index = 6
	elif position[1] < 700 : z_index = 3
	
	pass
