extends CanvasLayer

class_name ProjectLogPanel

enum TAG_TYPE{VERSION=0,FIX=1,FEATURE=2,TOOL=3}

const TAG_TYPE_COLOR_DICT = {
	TAG_TYPE.VERSION: Color.SKY_BLUE,
	TAG_TYPE.FIX: Color.RED,
	TAG_TYPE.FEATURE: Color.AQUAMARINE,
	TAG_TYPE.TOOL: Color.ORCHID
	}

const TAG_DICT = {
	TAG_TYPE.VERSION:["demo","0.1","1.0"],
	TAG_TYPE.FIX:["bugfix","uxfix"],
	TAG_TYPE.FEATURE:["code","design","ui","audio","art","animation"],
	TAG_TYPE.TOOL:["art_tool","log_tool","manage_tool"],
}

#const LOG_CONFIG_KEY_prefix = "log_panel_json_"
const LOG_DATA_DIR = "res://log/logger/logs/"
var log_files = []
var current_log_file

const IMAGE_DIR = ""

@onready var add_btn := %Add
@onready var save_btn := %Save
@onready var archives_btn := %Archives as MenuButton
@onready var archives_label := %ArchiveLabel as Label
@onready var log_items_container = %LogItemsContainer

const LOG_ITEM_GROUP = "log_item"
const LOG_ITEM_GROUP_MENBER = "log_item[{0}]"

var log_item_scene = preload("res://log/logger/project_log_panel_item.tscn")

var data = {"items":[]} as Dictionary

func _ready():
	add_btn.pressed.connect(_on_add)
	save_btn.pressed.connect(save_logs)
	archives_btn.get_popup().id_pressed.connect(_on_archive_switch)
	_load_archives()
	_on_archive_switch(log_files.find("v-demo-mountwuwang.json"))
	# var quat = Quaternion.from_euler(Vector3(deg_to_rad(10),0,deg_to_rad(10)))
	# print(quat)
	# quat = quat.normalized()
	# print(quat)
	# quat = Quaternion(Vector3(1,0,0),deg_to_rad(10)) * Quaternion(Vector3(0,0,1),deg_to_rad(10)) 
	# print(quat)
	# quat = quat.normalized()
	# print(quat)
	
func _load_archives():
	log_files = DirAccess.get_files_at(LOG_DATA_DIR) as PackedStringArray
	if log_files.size() == 0:
		printerr("_load_archives no file exists:",LOG_DATA_DIR)
	for i in range(0,log_files.size()):
		archives_btn.get_popup().add_item(log_files[i],i)
	_on_archive_switch(0)
	
func _load_logs():
	var path = _get_curr_path()
	if !FileAccess.file_exists(path):
		printerr("_load_logs no file exists:",path)
		return
	var json = ResourceLoader.load(path,"",ResourceLoader.CACHE_MODE_IGNORE)
	#print("load data=",json.data)
	print("loaded data")
	data = json.data
	if !data.has("items"):
		data["items"] = []
	_refresh_items()

func _get_curr_path():
	return LOG_DATA_DIR + current_log_file
	
func _refresh_items():
	var items = data["items"] as Array
	get_tree().call_group(LOG_ITEM_GROUP, "queue_free")
	for i in range(items.size()):
		var item_instance = log_item_scene.instantiate() as Control
		item_instance.add_to_group(LOG_ITEM_GROUP)
		item_instance.add_to_group(LOG_ITEM_GROUP_MENBER.format([]))
		item_instance.update.connect(_on_log_item_update.bind(i))
		#item_instance.save.connect(_on_log_item_save.bind(i))
		item_instance.remove.connect(_on_log_item_remove.bind(i))
		log_items_container.add_child(item_instance)
		if items[i] is Dictionary:
			item_instance.load_item(items[i])
		elif items[i] is String:
			var item_dict = JSON.parse_string(items[i])
			item_instance.load_item(item_dict)
		else :
			push_error("unknow type items[",i,"]=",items[i])

func save_logs():
	var path = _get_curr_path()
	if !FileAccess.file_exists(path):
		printerr("save_logs no file exists:",path)
		return
	#print("save logs data=", data)
	print("saved logs")
	var file := FileAccess.open(path, FileAccess.WRITE_READ) as FileAccess
	file.store_string(JSON.stringify(data, "\t"))
	file.close()

func _on_log_item_update(item:LogItem.ItemData, index:int):
	var json = item.to_json_dict()
	print("_on_log_item_update item=", json)
	data["items"][index] = json

func _on_log_item_save(item:LogItem.ItemData, index:int):
	var json = item.to_json_dict()
	print("_on_log_item_save item=", json)
	data["items"][index] = json
	save_logs()

func _on_log_item_remove(index:int):
	(data["items"] as Array).remove_at(index)
	save_logs()
	# reset index for each item
	_refresh_items()
	
func _on_add():
	(data["items"] as Array).push_front({})
	save_logs()
	# reset index for each item
	_refresh_items()

func _on_archive_switch(id:int):
	current_log_file = log_files[id]
	archives_label.text = log_files[id]
	_load_logs()
	
func _unhandled_input(event):
	if event.is_action("save"):
		save_logs()
