extends Control

@onready var weapon_scene = preload("res://scene/ui/item/weapon_item.tscn")

var item_layout_offset_x : int = 32
var item_layout_offset_y : int = 16

var weapon_item_list = []
var weapon_list : Array
var weapon_index : int
var weapon_index_dir : int
var weapon_index_rate : float
var hide_duration : float

func _process(delta):
	if not visible:
		return
	if weapon_index_dir:
		item_lerp(weapon_index_dir,weapon_index_rate)
		hide_duration = Setting.weapon_hide_duration
		return
	item_lerp(weapon_index_dir,1)
	hide_duration -= delta
	if hide_duration <= 0:
		for item in weapon_item_list:
			remove_child(item)
		weapon_item_list.clear()
		visible = false

func on_weapon_list_changed(list:Array):weapon_list = list
func on_weapon_index_changed(index:int):weapon_index = index
func on_weapon_index_change_rate_changed(rate:float):weapon_index_rate = rate
func on_weapon_index_change_dir_changed(dir:int):
	weapon_index_dir = dir
	if not weapon_index_dir:
		return
	if not visible:
		visible = true
		for i in range(5):append()
	else:
		if dir > 0:
			push_back()
			pop_front()
		else:
			push_front()
			pop_back()
	hide_duration = Setting.weapon_hide_duration

func append():weapon_item_list.append(create_weapon_item(len(weapon_item_list)-2+weapon_index_dir))
func push_front():weapon_item_list.push_front(create_weapon_item(-2+weapon_index_dir))
func push_back():weapon_item_list.push_back(create_weapon_item(2+weapon_index_dir))
func pop_front():remove_child(weapon_item_list.pop_front())
func pop_back():remove_child(weapon_item_list.pop_back())

func create_weapon_item(offset:int)->WeaponItemSub:
	var weapon_count = len(weapon_list)
	var index = ((weapon_index + offset) % weapon_count + weapon_count) % weapon_count
	var weapon_item_sub = weapon_scene.instantiate() as WeaponItemSub
	var weapon_cfg = weapon_list[index] as WeaponCfg
	add_child(weapon_item_sub)
	weapon_item_sub.init(weapon_cfg.icon)
	return weapon_item_sub

func item_lerp(dir:int,rate:float):
	for i in range(len(weapon_item_list)):
		var item = weapon_item_list[i] as WeaponItemSub
		var target_index = i-2
		var index = target_index+dir
		var pos_from = get_item_pos(index)
		var pos_to = get_item_pos(target_index)
		var alpha_from = 1 if abs(index)<=1 else 0
		var alpha_to = 1 if abs(target_index)<=1 else 0
		item.position = lerp(pos_from,pos_to,rate)
		item.update_alpha(alpha_from,alpha_to,rate)

func get_item_pos(offset:int):
	return Vector2(item_layout_offset_x*offset,item_layout_offset_y if offset else 0)
