extends Node

export(float) var frames_per_second = 5.0

var is_active:bool = false
var is_saving:bool = false

var _frametick = 1.0/frames_per_second
var _thread:Thread

var images = []


func _ready():
	_thread = Thread.new()


func _process(delta):
	if Input.is_action_just_pressed("controls_capture") && not is_saving:
		is_active = not is_active
		find_node("recording").set_visible(is_active)
		if not is_active:
			is_saving = true
			find_node("saving").set_visible(true)
			_thread.start(self, "save_images")
	if is_active:
		_frametick += delta
		if (_frametick > 1.0/frames_per_second):
			get_viewport().set_clear_mode(Viewport.CLEAR_MODE_ONLY_NEXT_FRAME)
			var img = get_viewport().get_texture().get_data()
			img.flip_y()
			images.append(img)


func save_images(userdata):
	var dir = Directory.new()
	var timestamp = OS.get_unix_time()
	if dir.open("user://capture/") != OK:
		dir.open("user://")
		dir.make_dir("capture")

	dir.open("user://capture/")
	dir.make_dir(str(timestamp))

	for img in images:
		img.save_png("user://capture/" + str(timestamp) + "/" + str(img) + ".png")

	images = []
	is_saving = false
	find_node("saving").set_visible(false)

	if(_thread.is_active()):
		_thread.wait_to_finish()