extends Node3D
class_name Weapon

const DEFAULT = 0
const INITIAL = 1
const SHOOT = 2
const RELOAD = 3

const DRAW_TIME = 0.35

var MELEE : bool
var MAX_CLIP : int
var DAMAGE : float
var MOMENTUM : Vector2
var ANGULAR_MOMENTUM : Vector3
var RECOIL_COOLDOWN : float
var RPM: float
var DRAW_POS : Vector3
var DRAW_ROT : Vector3
var MODEL : Node3D
var FIREMODE : int 
var HITSCAN : bool
var RAY_LEN : float = 1000 
var RELOAD_TIME : float
var RELOAD_MOMENTUM : Vector3
var RELOAD_ANGULAR_MOMENTUM : Vector3

var SHOOTING_SPEED: float
var can_shoot : bool
var clip : int
var state = DEFAULT
var tween : Tween

func stop_tween():
	if(tween.is_running()):
		tween.stop()

func init():
	state = DEFAULT
	SHOOTING_SPEED = 60.0 / RPM
	if(tween != null && tween.is_running()):
		tween.stop()

	MODEL.position = DRAW_POS
	MODEL.rotation = DRAW_ROT

	can_shoot = true
	InitialPos(DRAW_TIME, DRAW_TIME)


	
func InitialPos(draw_time, ready_time):
	tween = create_tween()
	tween.set_trans(Tween.TRANS_QUAD)
	
	tween.set_parallel(true)
	tween.tween_property(MODEL, "position", Vector3.ZERO, draw_time)
	tween.tween_property(MODEL, "rotation", Vector3.ZERO, draw_time)
	tween.tween_callback(func(): state = INITIAL).set_delay(ready_time)



func Shoot():
	if CanShoot():
		if not FIREMODE:
			can_shoot = false
		if not MELEE:
			clip -= 1
			
		state = SHOOT;
		tween = create_tween()
		tween.set_trans(Tween.TRANS_ELASTIC)
		tween.set_ease(Tween.EASE_OUT)
		tween.set_parallel(true)
		tween.tween_property(MODEL, "position", Vector3(.0, MOMENTUM.x, MOMENTUM.y), RECOIL_COOLDOWN / 2)
		var rand_rot_y = randf_range(-ANGULAR_MOMENTUM.y,ANGULAR_MOMENTUM.y)
		var rand_rot_z = randf_range(-ANGULAR_MOMENTUM.z,ANGULAR_MOMENTUM.z)
		tween.tween_property(MODEL, "rotation", Vector3(deg_to_rad(ANGULAR_MOMENTUM.x),deg_to_rad(rand_rot_y),deg_to_rad(rand_rot_z)),RECOIL_COOLDOWN /2)
		tween.tween_callback(func(): InitialPos(RECOIL_COOLDOWN / 2, SHOOTING_SPEED / 2)).set_delay(SHOOTING_SPEED / 2)
		return true
	return false

func CanShoot():
	return clip > 0 && state == INITIAL && can_shoot

func Release():
	if !FIREMODE:
		can_shoot = true


func Reload():
	if(clip < MAX_CLIP && state == INITIAL):
		state = RELOAD
		tween = create_tween()
		tween.set_trans(Tween.TRANS_CIRC)
		tween.set_ease(Tween.EASE_IN)
		tween.set_parallel(true)
		tween.tween_property(MODEL, "position", RELOAD_MOMENTUM, RELOAD_TIME)
		tween.tween_property(MODEL, "rotation", RELOAD_ANGULAR_MOMENTUM, RELOAD_TIME)
		tween.tween_callback(init).set_delay(RELOAD_TIME)
		clip = MAX_CLIP
		return true
	return false
