extends RigidBody2D

enum { INIT, GAME, GOD, DEAD}
var state = INIT
var screen_size = Vector2.ZERO

@export var power_engine = 300
@export var power_speen = 6000
@export var fire_rate = 0.25
@export var bullet_scene : PackedScene

var is_shoot_enabled = true
var thrust = Vector2.ZERO
var arg = 0 # pointing direction

func state_changer(new_state):
	match new_state:
		INIT:
			$CollisionShape2D.set_deferred("disabled", true)
		GAME:
			$CollisionShape2D.set_deferred("disabled", false)
		GOD: 
			$CollisionShape2D.set_deferred("disabled", true)
		DEAD:
			$CollisionShape2D.set_deferred("disabled", true)
	state = new_state
# Called when the node enters the scene tree for the first time.

func shoot():
	is_shoot_enabled = false
	$Colldown.start()
	var b = bullet_scene.instantiate()
	get_tree().root.add_child(b)
	b.start($Gun.global_transform)


func _ready():
	screen_size = get_viewport_rect().size
	state_changer(GAME)
	$Colldown.wait_time = fire_rate


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
	get_input()
	constant_force = thrust
	constant_torque = arg * power_speen
	
func get_input():
	thrust = Vector2.ZERO
	if state in [INIT, DEAD]:
		return
	if Input.is_action_pressed("thrust"):
		print(transform.x)
		print("position:" + str(position.x) + ", " + str(position.y))
		thrust = transform.x * power_engine
		
	arg = Input.get_axis("rotateLeft","rotateRight")
	if Input.is_action_pressed("shoot") && is_shoot_enabled:
		shoot()


func _integrate_forces(physics_state: PhysicsDirectBodyState2D):
	var new_spase_transform = physics_state.transform
	#print("x_0:" + str(new_spase_transform.origin.x))
	new_spase_transform.origin.x = wrapf(new_spase_transform.origin.x,0,screen_size.x)
	#print("x_1:" + str(new_spase_transform.origin.x))
	new_spase_transform.origin.y = wrapf(new_spase_transform.origin.y,0,screen_size.y)
	physics_state.transform = new_spase_transform
	

func _on_colldown_timeout():
	is_shoot_enabled = true
