@tool
extends EditorScenePostImport

func check_dir(path: String) -> void:
	var dir = DirAccess.open(path);
	if !dir:
		dir = DirAccess.open("res://");
		dir.make_dir_recursive(path);

func modify_resource(node: MeshInstance3D, path: String) -> void:
	var res = ResourceLoader.load(path, "Mesh", ResourceLoader.CACHE_MODE_REPLACE_DEEP);
	res = node.mesh;
	res.take_over_path(path);
	print("Reference COunt: " + str(res.get_reference_count()));
	var error = ResourceSaver.save(res, path, ResourceSaver.FLAG_CHANGE_PATH + ResourceSaver.FLAG_REPLACE_SUBRESOURCE_PATHS);
	res.emit_changed();
	if (error):
		print("Error: " + str(error));
	if (!error):
		print("resource file [" + node.name + "] SAVED");

func save_new_resource(node: MeshInstance3D, path: String) -> void:
	var error = ResourceSaver.save(node.mesh, path, ResourceSaver.FLAG_NONE);
	if (error):
		print("Error: " + str(error));
	if (!error):
		print("resource file [" + node.name + "] SAVED");

func op_resource(node: Node, path: String) -> void:
	if (node is not MeshInstance3D): print(node.name + " is NOT a MeshInstance3D"); return;
	
	var child_path: String = path + node.name + ".tres";
	if ResourceLoader.exists(child_path):
		print("resource [" + child_path + "] already exists");
		modify_resource(node, child_path);
	else:
		print("resource [" + child_path + "] does NOT exist");
		save_new_resource(node, child_path);

func iterate(node: Node, path: String) -> void:
	for child in node.get_children():
			op_resource(child, path);

# Called by the editor when a scene has this script set as the import script in the import tab.
func _post_import(scene: Node) -> Object:
	if scene != null:
		var name: String = scene.name;
		var path: String = "res://assets/meshes/imported/" + "_" + name;
		#path = "res://";
		print("Importing " + name);
		
		check_dir(path);
		
		path += "/";
		iterate(scene, path);
	return scene # Return the modified root node when you're done.
