--[[
	PushableVehicleFix
	Specialization to fix some issues for the pushable vehicle!
	
	@author:    Ifko[nator]
	@date:      15.03.2025
	@version:	3.0

	History:	v1.0 @09.02.2021 - initial implementation in FS 19
				--------------------------------------------------
				v2.0 @25.01.2022 - convert to FS 22
				--------------------------------------------------
				v3.0 @15.03.2025 - convert to FS 25
]]

PushableVehicleFix = {};

function PushableVehicleFix:onLoad(savegame)
	local xmlFile = loadXMLFile("vehicle", self.xmlFile.filename);

	local alwaysTurnedOn = false;
	local foundModName = self.xmlFile.filename:find("FS25_lsfmFarmEquipmentPack");

	if foundModName ~= nil then
		alwaysTurnedOn = foundModName > 0;
	end;

	self.spec_motorized.alwaysTurnedOn = Utils.getNoNil(getXMLBool(xmlFile, "vehicle.motorized#alwaysTurnedOn"), alwaysTurnedOn);

	delete(xmlFile);
end;

Motorized.onLoad = Utils.appendedFunction(Motorized.onLoad, PushableVehicleFix.onLoad);

function PushableVehicleFix:onStateChange(superFunc, state, vehicle, isControlling)
	if state == VehicleStateChange.ENTER_VEHICLE then
		if g_currentMission.missionInfo.automaticMotorStartEnabled and self:getCanMotorRun() or self.spec_motorized.alwaysTurnedOn then
			self:startMotor(true);
		end;
	elseif state == VehicleStateChange.LEAVE_VEHICLE then
		if self:getStopMotorOnLeave() and g_currentMission.missionInfo.automaticMotorStartEnabled then
			self:stopMotor(true);
		end;

		self:stopVehicle();
	end;
end;

Motorized.onStateChange = Utils.overwrittenFunction(Motorized.onStateChange, PushableVehicleFix.onStateChange);

function PushableVehicleFix.actionEventToggleMotorState(self, superFunc, actionName, inputValue, callbackState, isAnalog)
    if not self:getIsAIActive() and not self.spec_motorized.alwaysTurnedOn then
        local motorState = self:getMotorState();

        if motorState == MotorState.STARTING or motorState == MotorState.ON then
            self:stopMotor();
        else
            if self:getCanMotorRun() then
                self:startMotor();
            else
                local warning = self:getMotorNotAllowedWarning();

                if warning ~= nil then
                    g_currentMission:showBlinkingWarning(warning, 2000);
                end;
            end;
        end;
    end;
end;

Motorized.actionEventToggleMotorState = Utils.overwrittenFunction(Motorized.actionEventToggleMotorState, PushableVehicleFix.actionEventToggleMotorState);