class_name Mover extends Node

var speed = 1.0

func _input(event):
	return

func to_move_rotate(global_transform, delta: float):
	var mv = Vector3.ZERO
	var rot = 0.0
	for state in _states():
		var duo = _duo_for_state(global_transform, delta, state)
		mv += duo[0]
		rot += duo[1]
	return [mv, rot]
	
var state_move_forward = false
var state_move_left = false
var state_move_backward = false
var state_move_right = false
var state_turn_left = false
var state_turn_right = false

enum {
	STATE_MOVING_FORWARD,
	STATE_MOVING_LEFT,
	STATE_MOVING_RIGHT,
	STATE_MOVING_BACKWARD,
	STATE_TURNING_LEFT,
	STATE_TURNING_RIGHT,
	STATE_IDLE
}

func _states():
	var result  = _states_moving() + _states_turning()
	if result.is_empty():
		result = [STATE_IDLE]
	return result
	
func _states_moving():
	var moving_forward = self.state_move_forward and not self.state_move_backward
	var moving_left = self.state_move_left and not self.state_move_right
	var moving_right = self.state_move_right and not self.state_move_left
	var moving_backward = self.state_move_backward and not self.state_move_forward
	if moving_forward and moving_left:
		return [STATE_MOVING_LEFT, STATE_MOVING_FORWARD]
	elif moving_forward and moving_right:
		return [STATE_MOVING_RIGHT, STATE_MOVING_FORWARD]
	elif moving_forward:
		return [STATE_MOVING_FORWARD]
	elif moving_backward and moving_left:
		return [STATE_MOVING_LEFT, STATE_MOVING_BACKWARD]
	elif moving_backward and moving_right:
		return [STATE_MOVING_RIGHT, STATE_MOVING_BACKWARD]
	elif moving_backward:
		return [STATE_MOVING_BACKWARD]
	elif moving_left:
		return [STATE_MOVING_LEFT]
	elif moving_right:
		return [STATE_MOVING_RIGHT]
	return []
	
func _states_turning():
	if self.state_turn_left and not self.state_turn_right:
		return [STATE_TURNING_LEFT]
	elif self.state_turn_right and not self.state_turn_left:
		return [STATE_TURNING_RIGHT]
	return []

func _duo_for_state(global_transform, delta: float, state):
	var direction = Vector2.ZERO
	var rotation = 0.0
	match state:
		STATE_MOVING_FORWARD:
			direction.y = -1
		STATE_MOVING_BACKWARD:
			direction.y = 1
		STATE_MOVING_LEFT:
			direction.x = -1
		STATE_MOVING_RIGHT:
			direction.x = 1
		STATE_TURNING_LEFT:
			rotation = speed * delta
		STATE_TURNING_RIGHT:
			rotation = -speed * delta
		STATE_IDLE:
			pass
	if direction == Vector2.ZERO:
		return [Vector3.ZERO, rotation]
	direction = direction.normalized()
	
	var forward = global_transform.basis.z
	var right = global_transform.basis.x
	var relative_direction = (forward * direction.y + right * direction.x)
	
	relative_direction.x *= speed * delta
	relative_direction.z *= speed * delta
	#relative_direction.y = -speed
 
	return [relative_direction, rotation]
