--[[
    PlaceableVehicle

	Adds the possibility to load a placeable with pre placed vehicles.

	@author: 		TN47
	@contributor: 	BayernGamers
	@date: 			02.03.2025
	@version:		2.0

	History:		v1.0 @unknown - initial implementation in FS 22
					-------------------------------------------------------------------------------------------
					v2.0 @02.03.2025 - convert to FS 25, adjustments
]]

source(Utils.getFilename("scripts/utils/VehicleLoadingUtil.lua", g_currentModDirectory))

PlaceableVehicle = {
	specEntryName = string.format("spec_%s.placeableVehicle", g_currentModName)
}

function PlaceableVehicle.prerequisitesPresent(specializations)
	return true
end

function PlaceableVehicle.registerFunctions(placeableType)
	SpecializationUtil.registerFunction(placeableType, "onVehicleLoaded", PlaceableVehicle.onVehicleLoaded)
	SpecializationUtil.registerFunction(placeableType, "onVehicleDelete", PlaceableVehicle.onVehicleDelete)
end

function PlaceableVehicle.registerOverwrittenFunctions(placeableType)
	SpecializationUtil.registerOverwrittenFunction(placeableType, "canBeSold", PlaceableVehicle.canBeSold)
end

function PlaceableVehicle.registerEventListeners(placeableType)
	SpecializationUtil.registerEventListener(placeableType, "onLoad", PlaceableVehicle)
	SpecializationUtil.registerEventListener(placeableType, "onDelete", PlaceableVehicle)
end

function PlaceableVehicle.registerXMLPaths(schema, basePath)
	schema:setXMLSpecializationType("placeableVehicle")
	schema:register(XMLValueType.STRING, "placeable.vehicles.vehicle(?)#xmlFilename", "Vehicle xml filename")
	schema:register(XMLValueType.NODE_INDEX, "placeable.vehicles.vehicle(?)#linkNode", "Vehicle linkNode")
	--schema:register(XMLValueType.FLOAT, "placeable.vehicle#heightOffset", "Vehicle height offset")
	--schema:register(XMLValueType.FLOAT, "placeable.vehicle#yRotation", "Vehicle Y rotation offset")
	schema:setXMLSpecializationType()
end

function PlaceableVehicle:onLoad(savegame)
	local spec = self[PlaceableVehicle.specEntryName]
	spec.vehicles = {}

	local basePath = "placeable.vehicles.vehicle"

	if self.isServer then
		self.xmlFile:iterate(basePath,  function (_, vehicleKey)
			local filename = self.xmlFile:getValue(vehicleKey .. "#xmlFilename")

			if filename ~= nil then
				local xmlFilename = Utils.getFilename(filename, self.baseDirectory)
				local linkNode = self.xmlFile:getValue(vehicleKey .. "#linkNode", nil, self.components, self.i3dMappings) or self.rootNode
				local posX, posY, posZ = getWorldTranslation(linkNode)
				local dx, _, dz = localDirectionToWorld(linkNode, 0, 0, 1)
				local rotY = MathUtil.getYRotationFromDirection(dx, dz)
				
				if linkNode == self.rootNode then
					print("Warning: linkNode not found, using rootNode instead")
				end
				
				local location = {
					x = posX,
					y = posY,
					z = posZ
				}
				local rotation = {
					xRot = 0,
					yRot = rotY,
					zRot = 0
				}

				VehicleLoadingUtil.loadVehicleFromXML(xmlFilename, location, rotation, true, 0, VehiclePropertyState.NONE, self:getOwnerFarmId(), true, false, nil, nil, self.onVehicleLoaded, self, nil)
			end
		end)
	end
end

function PlaceableVehicle:onDelete()
	local spec = self[PlaceableVehicle.specEntryName]

	for i, vehicle in ipairs(spec.vehicles) do
		if vehicle ~= nil then
			vehicle:delete()

			spec.vehicles[i] = nil
		end
	end

	spec.vehicles = {}
end

function PlaceableVehicle:canBeSold(superFunc)
	local spec = self[PlaceableVehicle.specEntryName]

	for _, vehicle in ipairs(spec.vehicles) do
		if vehicle ~= nil and vehicle:getIsActive() then
			return false, g_i18n:getText("shop_messageReturnVehicleInUse")
		end
	end

	return superFunc(self)
end

function PlaceableVehicle:onVehicleLoaded(vehicles, vehicleLoadState, args)
	local spec = self[PlaceableVehicle.specEntryName]

	for _, vehicle in ipairs(vehicles) do
		if vehicle ~= nil then
			vehicle.isVehicleSaved = false
			vehicle:addDeleteListener(self, "onVehicleDelete")

			table.insert(spec.vehicles, vehicle)
		end
	end
end

function PlaceableVehicle:onVehicleDelete(vehicle)
	local spec = self[PlaceableVehicle.specEntryName]

	for i, veh in ipairs(spec.vehicles) do
		if veh == vehicle then
			table.remove(spec.vehicles, i)
			self:delete()
		end
	end
end