extends Node



#scene changing
var _scenelist = [
	"res://mainScene/Main.tscn",
	"res://oscScene/Scene.tscn",
	"res://cricketScene/Scene.tscn",
	"res://LieDownBeforeSleep/Scene.tscn"
	]
var _sceneidx = 0

func nextScene():
	_sceneidx = (_sceneidx + 1) % _scenelist.size()
	get_tree().change_scene(_scenelist[_sceneidx])



## copy directory recursively ==> we need godot 4 for this approach..
#func _copydirectory_recursive(src, dst):
#	var dotfolders = RegEx.new()
#	dotfolders.compile("^\\.\\w*")
#	var pdfiles = RegEx.new()
#	pdfiles.compile("\\w+\\.pd$")
#	var dir = Directory.new()
#	if dir.open(src) == OK:
#		dir.list_dir_begin()
#		var file_name = dir.get_next()
#		while file_name != "":
#			if dir.current_is_dir():
#				print("Found directory: " + file_name)
#				if not dotfolders.search(file_name):
#					dir.make_dir(dst + "/" + file_name)
#					_copydirectory_recursive(dir.get_current_dir() + "/" + file_name, dst + "/" + file_name)
#			else:
#				if pdfiles.search(file_name):
#					print("Found puredata file: " + file_name)
#				dir.copy(src + "/" + file_name, dst + "/" + file_name)
#
#			file_name = dir.get_next()
#	else:
#		print("An error occurred when trying to access the path. : " + src)


#gdpd (pd interface with godot)
var _gdpd
var _patches = []

func _ready():
	_gdpd = load("res://addons/gdpd/bin/gdpd.gdns").new()
	# var inps = _gdpd.get_available_input_devices()
	# var outs = _gdpd.get_available_output_devices()
	# _gdpd.init_devices(inps[0], outs[0])
	# set gui path to activate gui window (otherwise, nogui)
#	_gdpd.set_gui_path("/Applications/Pd-0.53-1.app/Contents/Resources")
	_gdpd.set_volume(1) # by default, volume(gain) == 0
	_gdpd.init(0, 2, 44100, 256)
	_gdpd.computeAudio(true) # [; pd dsp 1 (
	_gdpd.subscribe("toGodot")

	# duplicate "res://" into 'user://' ==> we need godot 4 for this approach..
#	_copydirectory_recursive("res://", "user://")


func _exit_tree():
	if _patches.size() != 0:
		print()
		print("! ======== * purging leftover opened patches ... * ======== !")
		print()
		for id in _patches:
			_gdpd.closePatch(id)
		_patches.clear()
	_gdpd.stop()

func load_patch(pd_patch) -> int:
	#the patch path should be the absolute one
	#separate file name from directory
	var patch_name = pd_patch.split("/")[-1]
	var patch_dir = pd_patch.trim_suffix(patch_name)

	#load patch
	var id = _gdpd.openPatch(patch_name, patch_dir)
	_patches.append(id)

	return id

func close_patch(id):
	if id in _patches:
		_gdpd.closePatch(id)
		_patches.erase(id)

func _process(_delta) :
	while _gdpd.has_message():
		var msg = _gdpd.get_next()
		print(msg)
#		if msg[0] == "random":
#			print("r")

# delaying stream start a bit to prevent start-up 'pop' noise.
func _on_Timer_timeout():
	_gdpd.streamstart()

