extends WindowDialog

var save_path = "user://saves"

var next_save_id = 0
var nosave = false
func _ready():
	print("save/load ready")
	$v/quit.connect("pressed", self, "exit_game")
	$v/return.connect("pressed", self, "close")
	$v/save/new_save.connect("pressed", self, "save_game")
	connect("about_to_show", self, "about_to_show")
	connect("popup_hide", self, "popup_hide")
func exit_game():
	controls.is_gui = false
	get_tree().quit()
func close():
	controls.is_gui = false
	hide()
func save_game():
	scenario.prepare_save_data()
	print("next_save_id: ", next_save_id)
	var filename = save_path + "/" + str(next_save_id) + ".sav"
	var f = File.new()
	if f.open(filename, File.WRITE) == OK:
		print("saving to ", filename)
		f.store_string(JSON.print(scenario.save_data, "\t", false))
		f.close()
	print("userdata = ", OS.get_user_data_dir())
	controls.is_gui = false
	hide()

func load_game(file_name):
	controls.is_gui = false
	nosave = false
	var f = File.new()
	if f.open(save_path + "/" + file_name, File.READ) == OK:
		var s = f.get_as_text()
		var result = JSON.parse(s)
		scenario.save_data = result.result
		scenario.restart_scene()
	else:
		print("Can't open ", file_name)
	hide()
func popup_hide():
	yield(get_tree().create_timer(0.5), "timeout")
	controls.is_gui = false
	hide()

func about_to_show():
	print("save/load about to show")
	if nosave:
		if $v/save/new_save.visible:
			$v/save/new_save.hide()
	else:
		if !$v/save/new_save.visible:
			$v/save/new_save.show()
	var d: = Directory.new()
	var f: = File.new()
	var theme = Theme.new()
	var font: DynamicFont = preload("res://fonts/DefaultFont.tres")
	theme.default_font = font
	for e in $v/save/s/v.get_children():
		e.queue_free()
	if d.dir_exists(save_path):
		if d.open(save_path) == OK:
			d.list_dir_begin()
			var file_name = d.get_next()
			while file_name != "":
				if file_name in [".", ".."]:
					file_name = d.get_next()
					continue
				var fid = file_name.replace(".sav", "")
				if fid.is_valid_integer():
					next_save_id = max(next_save_id, int(fid) + 1)
				print(file_name)
				var t = f.get_modified_time(save_path + "/" + file_name)
				var ts = OS.get_datetime_from_unix_time(t)
				var b = Button.new()
				b.theme = theme
				b.text = "Load " + str(ts.year) + "." + str(ts.month) + "." + str(ts.day)
				b.text += " " + str(ts.hour) + ":" + str(ts.minute) + ":" + str(ts.second)
				print(b.text)
				$v/save/s/v.add_child(b)
				b.connect("pressed", self, "load_game", [file_name])
				$v/save/s/v.update()
				$v/save/s.update()
				$v/save.update()
				$v.update()
				update()
				$v/quit.update()
				file_name = d.get_next()
			d.list_dir_end()
	else:
		d.make_dir_recursive(save_path)
	print("next_save_id: ", next_save_id)
	update()
