extends Position2D
## Represents a weapon that spawns and shoots bullets.
## The Cooldown timer controls the cooldown duration between shots.

export var scene_path :Resource
export var pew_cooldown_time :float = 1.0

const BULLET_VELOCITY = 350
var projectile :Projectile #preload("res://src/Projectile.tscn")

#onready var sound_shoot = $Shoot
onready var timer = Timer.new()
onready var offset_position = Vector2(transform.origin.x, transform.origin.y)

## I don't know what type this would be
var loaded_scene

func _ready():
	#projectile = load(scene_path.resource_path)
	loaded_scene = load(scene_path.resource_path)
	timer.autostart = false
	timer.wait_time = pew_cooldown_time
	timer.one_shot = true
	timer.autostart = false
	add_child(timer)


# This method is only called by Player.gd.
func shoot(direction = 1):
	#self.set_position(Vector2(position.x * direction, position.y))
	#transform.x = transform.x * direction
	#Transform2D.FLIP_Y
	#transform.origin.x = transform.origin.x * direction
#	if direction < 0:
#		var t = Transform2D()
#		# Translation
#		t.origin = Vector2(position.x * -1, position.y)
#		transform = t
#	elif direction > 0:
#		var t = Transform2D()
#		# Translation
#		t.origin = Vector2(position.x, position.y)
#		transform = t
		
	var normal_vector = (position * get_parent().transform.x).normalized()
	print("Fire Debug: ", direction, " Gun position: ", get_parent().transform.x, position, normal_vector)
	
#	position.x = position.x * direction  #shifting position before fire was unreliable
	if not timer.is_stopped():
		return false
	var bullet = loaded_scene.instance()
#	if (direction > 0):
#		bullet.global_position = global_position
#	else:
#		bullet.global_position = global_position - Vector2(position.x * 2, 0)
	if bullet is Projectile:
		bullet.global_position = global_position
		bullet.direction_normal = normal_vector

	#bullet.linear_velocity = Vector2(direction * BULLET_VELOCITY, 0)

	bullet.set_as_toplevel(true)
	add_child(bullet)
#	sound_shoot.play()
	timer.start()
	return true

