extends Node

const SUPPORTED_INPUT_EXT = [
	".jpeg", ".jpg", ".png", ".webp"
]

var cwd = "."

var shader_path = "":
	get():
		return shader_path
	set(v):
		shader_path = v
		if "/" in v: # update current working directory
			cwd = v.substr(0, v.rfind("/"))

var shader: Shader:
	get():
		if shader_path == "":
			return null
		print("Load ", shader_path)
		return load(shader_path)

var input_image_path = ""
var input_image_texture: ImageTexture
var last_input_image_path = ""

var last_image_savepath = ""
var result: Image

func get_absolute_path(p: String) -> String:
	# this only works on Linux!
	if !p.begins_with("/"):
		return self.cwd + "/" + p.lstrip("./")
	return p

func load_image() -> String: # returns an error message
	var supported = false
	for e in SUPPORTED_INPUT_EXT:
		if self.input_image_path.ends_with(e):
			supported = true
	if not supported:
		return "File extension not supported."
	print("Load ", self.input_image_path)
	var img = Image.new()
	var err = img.load(self.input_image_path)
	if err == OK:
		input_image_texture = ImageTexture.create_from_image(img)
		if self.last_image_savepath == "" or self.input_image_path != self.last_input_image_path:
			self.last_image_savepath = self.input_image_path
		self.last_input_image_path = self.input_image_path
		return ""
	return error_string(err) + " " + self.input_image_path

func save_result(path: String):
	print("Export ", path)
	var err = self.result.save_png(path)
	if err != OK:
		print("An error occured!")
	else:
		self.last_image_savepath = path
