extends Control

onready var taquin = $HSplitContainer/Taquin

func _ready():
	load_game()
	print("Starting state: ", taquin.current_state_name())

func _notification(what):
	if what == MainLoop.NOTIFICATION_WM_QUIT_REQUEST:
		save_game()
		get_tree().quit() # default behavior

# https://docs.godotengine.org/en/3.2/tutorials/io/saving_games.html
func save_game():
	var save_game = File.new()
	save_game.open("user://savegame.save", File.WRITE)
	var save_nodes = get_tree().get_nodes_in_group("Persist")
	for node in save_nodes:
		# Check the node has a save function
		if !node.has_method("save"):
			print("persistent node '%s' is missing a save() function, skipped" % node.name)
			continue

		# Call the node's save function
		var node_data = node.call("save")
		
		# Augment data with origin
		node_data["path"] = node.get_path()

		# Store the save dictionary as a new line in the save file
		save_game.store_line(to_json(node_data))
	save_game.close()

func load_game():
	var save_game = File.new()
	if not save_game.file_exists("user://savegame.save"):
		return # Error! We don't have a save to load.

	# Load the file line by line and process that dictionary to restore
	# the object it represents.
	save_game.open("user://savegame.save", File.READ)
	while save_game.get_position() < save_game.get_len():
		# Get the saved dictionary from the next line in the save file
		var node_data = parse_json(save_game.get_line())

		# Call the node's save function
		var node = get_node(node_data["path"])
		node.call("load", node_data)

	save_game.close()

#
# Signals
#
func _on_Taquin_state_changed(previous, new):
	print("Taquin state: ", Taquin.State.keys()[previous], " -> ", Taquin.State.keys()[new])
	match new:
		Taquin.State.WINNING:
			print("Solved!")
		Taquin.State.GAME_OVER:
			pass

func _on_New_game_pressed():
	$NewGamePanel.popup_centered(OS.window_size * 0.9)

func _on_NewGamePanel_about_to_show():
	$HSplitContainer/Taquin.set_process_input(false)

func _on_NewGamePanel_popup_hide():
	$HSplitContainer/Taquin.set_process_input(true)
