extends Node


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

export (bool) var _enable_gui = false
export (String) var _gui_path = "/Applications/Pd-0.53-1.app/Contents/Resources"

export (float) var _sample_rate = 48000
export (int) var _blocksize = 256

func _ready():
	_gdpd = load("res://addons/gdpd/bin/gdpd.gdns").new()
	if _enable_gui:
		# set gui path to activate gui window (otherwise, nogui)
		_gdpd.set_gui_path(_gui_path)
	_gdpd.set_volume(1) # by default, volume(gain) == 0
	_gdpd.init(0, 2, _sample_rate, _blocksize)
	_gdpd.computeAudio(true) # [; pd dsp 1 (
	_gdpd.subscribe("toGodot")
	# delayed 'stream start' to prevent start-up 'pop' noise.
	yield(get_tree().create_timer(0.3), "timeout")
	_gdpd.streamstart()

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)
	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")





# ==== archived. ====


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


## 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)
