var EDITOR_VERSION = "0.0.1"

var level
var is_saving = false



func _init(level_scene):
	self.level = level_scene

func save_level_file(filename):
	is_saving = true
	var level_cam_pos = self.level.camera_rig.pivot_game.position
	var level_cam_rot_x = self.level.camera_rig.pivot_game2.rotation.x
	var level_cam_rot_y = self.level.camera_rig.pivot_game.rotation.y
	if self.level.metadata.has("iteration"):
		self.level.metadata["iteration"] += 1
	if not self.level.metadata.has("name") or self.level.metadata["name"] != filename:
		self.level.metadata["name"] = filename
		self.level.metadata["iteration"] = 0
	self.level.metadata["editor_version"] = self.EDITOR_VERSION
	self.level.metadata["initial_cam_pos"] = [level_cam_pos.x, level_cam_pos.y ,level_cam_pos.z]
	self.level.metadata["initial_cam_rot"] = [level_cam_rot_x, level_cam_rot_y]
	
	var level_data = self.level.get_dict()

	LevelManager.save_level_to_file(filename, level_data)
	Settings.set_option("selected_level", filename)
	LevelManager.load_levels_from_dir()
	is_saving = false

func load_level_file(filename):
	print ("level to load: " + str(filename))
	Settings.set_option("selected_level", filename)
	var content = LevelManager.get_level_data(filename)
	if content.is_empty():
		return

	self.level.builder.wipe_level()
	self.level.builder.fill_level_from_data(content)
	self._initialize_camera_position()
	
	



func _initialize_camera_position():
	if self.level.metadata.has("initial_cam_pos"):

		
		var position = Vector3(self.level.metadata["initial_cam_pos"][0], self.level.metadata["initial_cam_pos"][1], self.level.metadata["initial_cam_pos"][2])
		var rotation = Vector2(self.level.metadata["initial_cam_rot"][0], self.level.metadata["initial_cam_rot"][1])
		self.level.camera_rig.snap_camera_position(position, "game")
		self.level.camera_rig.snap_camera_rotation(rotation, "game")

