extends Node

var player_data : Adventurer = null
var player : Player = null
var panel : GamePanel = null
var player_profile : Window = null
var quest_log : QuestLog = null
var top_menu : TopMenu = null
var open : bool = false
var end_shift_confirmation : ConfirmationDialog
var end_shift_confirm_template = preload("res://templates/end_shift_confirmation.tscn")
var player_profile_template = preload("res://templates/player_profile_window.tscn")
var last_screenshot : Image
func _ready() -> void:
	player_data = Adventurer.new()
	Quest.load_quest_list()
	DisplayServer.register_additional_output(self)
	end_shift_confirmation = end_shift_confirm_template.instantiate()
	add_child(end_shift_confirmation)
	
func _process(delta: float) -> void:
	if open:
		if Input.is_action_just_pressed("profile"):
			toggle_player_profile()
		if Input.is_action_just_pressed("switch modes"):
			confirm_end_shift()
		if Input.is_action_just_pressed("test"):
			test_save()
		
func add_quest_progress_bar(quest : Quest) -> void:
	panel.add_quest_progress_bar(quest)

func confirm_end_shift() -> void:
	end_shift_confirmation.popup_centered()

func setup_visitor_ui(spawner: VisitorSpawner)-> void:
	if panel:
		panel.connect_visitor_spawner(spawner)

func toggle_player_profile():
	if player_profile != null:
		player_profile.queue_free()
		player_profile = null
	else:
		player_profile = player_profile_template.instantiate()
		add_child(player_profile)
		player_profile.setup(player.data)

	
func end_shift() -> void:
	take_screenshot()
	open = false
	if player_profile != null:
		toggle_player_profile()
	panel.switch_panel(open)
	var window = get_window()
	window.mode = Window.MODE_WINDOWED
	var size = DisplayServer.screen_get_size()
	window.content_scale_size = Vector2i(415,700)
	var wsize = window.get_size_with_decorations()
	#window.position = Vector2i(size.x - 345, 25)
	window.transparent = true
	window.transparent_bg = true
	DisplayServer.window_set_flag(DisplayServer.WINDOW_FLAG_BORDERLESS, true)
	DisplayServer.window_set_flag(DisplayServer.WINDOW_FLAG_TRANSPARENT, true)
	#window.per
	Guild.hall.process_mode = Node.PROCESS_MODE_DISABLED
	Guild.hall.visible = false
	top_menu.hide()
	panel.get_parent().global_position = Vector2i(5,5)
	window.size = Vector2i(415,700)
	panel.populate_quest_views()
	panel.populate_quest_bars()

func notice(msg : String, time : float = 1) -> void:
	panel.notice(msg, time)

func calculate_kill_exp(killer : QuestSprite, killed : QuestSprite) -> int:
	return clamp(1, (killed.level - killer.level) * 5, 100)

func take_screenshot() -> void:
	last_screenshot = get_viewport().get_texture().get_image()
	
func test_save() -> void:
	if open:
		take_screenshot()
	var save_dict = {
		"savetime": Time.get_datetime_string_from_system(),
		"screenshot": last_screenshot
	}
	#Save the guild data
	save_dict["guildname"] = Guild.name
	save_dict["guildlevel"] = Guild.level
	#Save the player data
	if player:
		save_dict["playername"] = player.data.full_name()
		save_dict["playerlevel"] = player.data.level
	#Save the employee data
	#Save the adventurer data
	#Save the quest data
		#Save the quest progress
	var save_file = FileAccess.open("user://savefile.save", FileAccess.WRITE)
	save_file.store_line(JSON.stringify(save_dict))

func get_savefile_data(filename : String) -> Dictionary:
	var load_file = FileAccess.open("user://" + filename, FileAccess.READ)
	var json = JSON.new()
	var json_string = load_file.get_line()
	var parse_result = json.parse(json_string)
	if not parse_result == OK:
		printerr("JSON Parse Error: ", json.get_error_message(), " in ", json_string, " at line ", json.get_error_line())
		return {}
	var image = Image.new()
	var ss : String = json.data.screenshot
	#print(ss.data)
	image.load_png_from_buffer(ss.hex_decode())
	var data_dict = {
		"playername": json.data.playername,
		"playerlevel": json.data.playerlevel,
		"guildname": json.data.guildname,
		"guildlevel": json.data.guildlevel,
		"savetime": json.data.savetime,
		"screenshot": image
	}
	return data_dict

func test_load(filename : String) -> void:
	var load_file = FileAccess.open("user://" + filename, FileAccess.READ)
	var json = JSON.new()
	var json_string = load_file.get_line()
	var parse_result = json.parse_string(json_string)
	if not parse_result == OK:
		printerr("JSON Parse Error: ", json.get_error_message(), " in ", json_string, " at line ", json.get_error_line())
		return

func switch_scenes(scene_name : String) -> void:
	get_tree().change_scene_to_file("res://scenes/" + scene_name + ".tscn")

func switch_dialogue(timeline_name : String, label : String) -> void:
	Dialogic.start("res://dialogic/timelines/" + timeline_name + ".dtl", label)
	
func save_quests(save_dict : Dictionary) -> void:
	var lst = []
	for quest in Guild.quests:
		lst.append(quest.save_dict())
	save_dict.quests = lst
