--
-- OdpalanieMP
-- Specialization for manual Motor Ignition
--
-- @author  Templaer
-- @date  01/05/09
--
-- Modifikationen erst nach Rücksprache
-- Do not edit without my permission
--
-- Edited by Henly20 (ls-uk modteam) Made MP compatible
-- v2 Henly20 24 April 2012

OdpalanieMP = {};

function OdpalanieMP.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Motorized, specializations) and SpecializationUtil.hasSpecialization(Steerable, specializations) and SpecializationUtil.hasSpecialization(Hirable, specializations);
end;

function OdpalanieMP:load(xmlFile)

    -- Booleans
    self.ignitionKey = false;
	self.allowedIgnition = false;

	local aiMotorSound  = getXMLString(xmlFile, "vehicle.aiMotorSound#file");
	if aiMotorSound  ~= nil and aiMotorSound  ~= "" then
		aiMotorSound  = Utils.getFilename(aiMotorSound, self.baseDirectory);
        self.aiMotorSoundRadius = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.aiMotorSound#radius"), 50);
        self.aiMotorSoundInnerRadius = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.aiMotorSound#innerRadius"), 10);
        self.aiMotorSoundVolume = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.aiMotorSound#volume"), 1);
        self.aiMotorSound = createAudioSource("aiMotorSound", aiMotorSound, self.aiMotorSoundRadius, self.aiMotorSoundInnerRadius, self.aiMotorSoundVolume, 0);
        link(self.components[1].node, self.aiMotorSound);
        setVisibility(self.aiMotorSound, false);
	end;

	local motorStopSoundNew = getXMLString(xmlFile, "vehicle.motorStopSound#file");
	if motorStopSoundNew ~= nil and motorStopSoundNew ~= "" then
		motorStopSoundNew = Utils.getFilename(motorStopSoundNew, self.baseDirectory);
		self.motorStopSoundNew = createSample("motorStopSoundNew");
		loadSample(self.motorStopSoundNew, motorStopSoundNew, false);
		self.motorStopSoundNewPitchOffset = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.motorStopSound#pitchOffset"), 0);
		self.motorStopSoundNewVolume = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.motorStopSound#volume"), 1.0);
	end;

	self.playedMotorStopSoundNew = true;

	self.motorStopSoundVolume = 0;

	self.setIgnition = SpecializationUtil.callSpecializationsFunction("setIgnition");

    self.isMotorStarted = false;
	self.ignitionMode = 0;

	self.boardEngine = {};
	self.boardEngine[1] = Utils.indexToObject(self.components,getXMLString(xmlFile,"vehicle.boardEngine#index1"));
	self.boardEngine[2] = Utils.indexToObject(self.components,getXMLString(xmlFile,"vehicle.boardEngine#index2"));

	self.batteryLightActive = false;
	self.oilLightActive = false;
	self.keySwitchR	= false;
	self.keySwitch = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.keySwitch#index"));	
	self.keySwitch1 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.keySwitch1#index"));	
	
    self.printWarningTime = 0;
end;

function OdpalanieMP:delete()
end;

function OdpalanieMP:readStream(streamId, connection)
	local ignition = streamReadInt8(streamId);
	self:setIgnition(ignition, true);
end;

function OdpalanieMP:writeStream(streamId, connection)
	streamWriteInt8(streamId, self.ignitionMode);
end;

function OdpalanieMP:mouseEvent(posX, posY, isDown, isUp, button)
end;

function OdpalanieMP:keyEvent(unicode, sym, modifier, isDown)
end;

function OdpalanieMP:update(dt)
	if self:getIsActiveForInput() then
		if InputBinding.hasEvent(InputBinding.Odpalanie) then
			if self.ignitionMode > 2 then
				self.ignitionMode = 0;
			end;
				self:setIgnition(math.abs(self.ignitionMode + 1));
			end;
			if InputBinding.isPressed(InputBinding.Odpalanie) and self.ignitionMode == 2 then
				setRotation(self.keySwitch1, 0, Utils.degToRad(-20), 0);
				else		
				setRotation(self.keySwitch1, 0, Utils.degToRad(0), 0);
			end;
			if InputBinding.isPressed(InputBinding.Warning) and self.ignitionMode == 0 then
			self.printWarningTime = self.time + 700;
		end;
	end;
end;

function OdpalanieMP:updateTick(dt)

		acceleration = -InputBinding.getAnalogInputAxis(InputBinding.AXIS_MOVE_FORWARD_VEHICLE);
		if InputBinding.isAxisZero(acceleration) then
			acceleration = -InputBinding.getDigitalInputAxis(InputBinding.AXIS_MOVE_FORWARD_VEHICLE);
		end;
			-- Does not execute when AI is activated
		if not self.isHired then
				-- Handles ignition key input
			if self.ignitionKey and self.allowedIgnition then
			self:startMotor(true);
			self.allowedIgnition = false;
			self.deactivateOnLeave = false;
			Utils.setEmittingState(self.exhaustParticleSystems, true)
		elseif not self.ignitionKey and self.allowedIgnition then
			self:stopMotor(true);
			self.allowedIgnition = false;
			self.deactivateOnLeave = true;
			setVisibility(self.aiMotorSound, false);
			-- Brakes the wheels upon turning off the engine
			for k,wheel in pairs(self.wheels) do
				setWheelShapeProps(wheel.node, wheel.wheelShape, 0, self.motor.brakeForce, 0);
			end;
			self:onDeactivateAttachements();
		end;

		if self.playedMotorStopSoundNew == false then
			playSample(self.motorStopSoundNew, 1, self.motorStopSoundNewVolume, 0);
			self.playedMotorStopSoundNew = true;
		end;
		-- Prevents the AI from driving when engine is off
		elseif not self.ignitionKey and not self.deactivateOnLeave then
			WheelsUtil.updateWheelsPhysics(self, dt, self.lastSpeed, 0, false, 0);
		end;
		
		if self.keySwitchR then
			setRotation(self.keySwitch, 0, Utils.degToRad(-20), 0);
		end;
		if not self.keySwitchR then
			setRotation(self.keySwitch, 0, Utils.degToRad(0), 0);
		end;
		if self.fuelFillLevel == 0 then
		self.ignitionMode = 0; 
        self.isAITractorActivated = false;
		self.ignitionKey = false;
		self:stopMotor(true);
		self.allowedIgnition = false;
		self.deactivateOnLeave = true;
		setVisibility(self.aiMotorSound, false);
		self.lastAcceleration = 0;
			if self.isServer then
				for k,wheel in pairs(self.wheels) do
					setWheelShapeProps(wheel.node, wheel.wheelShape, 0, self.motor.brakeForce, 0);
				end;
			end;
		end;

		setVisibility(self.boardEngine[1], self.batteryLightActive);
		setVisibility(self.boardEngine[2], self.oilLightActive);

		local xt,yt,zt = getTranslation(self.components[1].node);
		local deltaWater = yt-g_currentMission.waterY+2.5;
		if deltaWater < 0 then
			self.ignitionMode = 0;
			self.ignitionKey = false;
			self:stopMotor(true);
			self.allowedIgnition = false;
			self.deactivateOnLeave = true;
			setVisibility(self.aiMotorSound, false);
			self.lastAcceleration = 0;
			if self.isServer then
				for k,wheel in pairs(self.wheels) do
					setWheelShapeProps(wheel.node, wheel.wheelShape, 0, self.motor.brakeForce, 0);
				end;
			end;
		end;
        if self.ignitionMode == 2 and (not self:getIsActive() or self:getIsHired()) then
            local fuelUsed = self.fuelUsage*0.4;
            self:setFuelFillLevel(self.fuelFillLevel-fuelUsed);
            g_currentMission.missionStats.fuelUsageTotal = g_currentMission.missionStats.fuelUsageTotal + fuelUsed;
            g_currentMission.missionStats.fuelUsageSession = g_currentMission.missionStats.fuelUsageSession + fuelUsed;
		elseif self.ignitionMode == 2 and self.isServer and self:getIsActive() and self.movingDirection == 0 then
            if not self:getIsHired() then
				local fuelUsed = self.fuelUsage*0.3;
				self:setFuelFillLevel(self.fuelFillLevel-fuelUsed);
				g_currentMission.missionStats.fuelUsageTotal = g_currentMission.missionStats.fuelUsageTotal + fuelUsed;
				g_currentMission.missionStats.fuelUsageSession = g_currentMission.missionStats.fuelUsageSession + fuelUsed;
 		   end;
        end;
	if self.ignitionMode == 0 or self.ignitionMode == 1 then
		self.isHired = false;
		self.isAITractorActivated = false;			
	end;
end;

function OdpalanieMP:onLeave()
    if not self.deactivateOnLeave then
	    Utils.setEmittingState(self.exhaustParticleSystems, true)
		self.allowedIgnition = false;
		self.isMotorStarted = true;
		self.ignitionKey = true;
		if self.ignitionMode == 2 then
			setVisibility(self.aiMotorSound, true);
		end;

		-- Brakes the wheels upon turning off the engine
        self.lastAcceleration = 0;
        if self.isServer then
            for k,wheel in pairs(self.wheels) do
                setWheelShapeProps(wheel.node, wheel.wheelShape, 0, self.motor.brakeForce, 0);
            end;
        end;
	else
		self.allowedIgnition = false;
		self.ignitionKey = false;
		self.keySwitchR	= false;
		if self.ignitionMode == 0 or self.ignitionMode == 1 then
			setVisibility(self.aiMotorSound, false);
		end;
	end;
end;

function OdpalanieMP:onEnter()
	-- Prevents the engine from starting upon entering
	if not self.ignitionKey then
		self.isMotorStarted = false;
		Motorized.stopSounds(self);
		Utils.setEmittingState(self.exhaustParticleSystems, false)
		if self.ignitionMode == 0 then
			setVisibility(self.aiMotorSound, false);
		end;
	else
		if self.ignitionMode == 2 then
			setVisibility(self.aiMotorSound, true);
			self.batteryLightActive = false;
			self.allowedIgnition = true;
			self.oilLightActive = false;
			self.ignitionKey = true;
			self.keySwitchR = true;
		end;	
	end;
end;

function OdpalanieMP:draw()
    if self.isClient then
		if self.printWarningTime > self.time then
			g_currentMission:addWarning(g_i18n:getText("Odpalanie"));
		end;
	end;
end;

function OdpalanieMP:setIgnition(ignition, noEventSend)
	IgnitionEvent.sendEvent(self, ignition, noEventSend);

	self.ignitionMode = ignition;
	self.keySwitchR = false;
	self.batteryLightActive = false;
	self.oilLightActive = false;
    self.ignitionKey = false;
	self:stopMotor(true);
	self.allowedIgnition = false;
	self.deactivateOnLeave = true;
	setVisibility(self.aiMotorSound, false);
    self.lastAcceleration = 0;
    if self.isServer then
        for k,wheel in pairs(self.wheels) do
            setWheelShapeProps(wheel.node, wheel.wheelShape, 0, self.motor.brakeForce, 0);
        end;
    end;

	if self.ignitionMode == 0 then
		self.batteryLightActive = false;
		self.oilLightActive = false;
		self.ignitionKey = false;
		self.allowedIgnition = false;  
		self.keySwitchR = false;
	end;
	if self.ignitionMode == 1 then
		self.ignitionKey = false;
		self.allowedIgnition = false;
		self.batteryLightActive = true;
		self.oilLightActive = true;
		self.keySwitchR = true;
	end;
	if self.ignitionMode == 2 then
		self.batteryLightActive = false;
		self.oilLightActive = false;
		self.ignitionKey = true;
		self.keySwitchR = true;
		self.allowedIgnition = true;
	end;
	if self.ignitionMode > 2 then
		self.ignitionMode = 0;
		self.allowedIgnition = false;
		self.ignitionKey = false;
		self:stopMotor(true);
		self.playedMotorStopSoundNew = false;
	end;

	if self.ignitionKey and self.allowedIgnition then
		self:startMotor(true);
		self.allowedIgnition = false;
		self.deactivateOnLeave = false;
		Utils.setEmittingState(self.exhaustParticleSystems, true)
	elseif not self.ignitionKey and self.allowedIgnition then
		self:stopMotor(true);
		self.allowedIgnition = false;
		self.deactivateOnLeave = true;
		setVisibility(self.aiMotorSound, false);
		-- Brakes the wheels upon turning off the engine
		for k,wheel in pairs(self.wheels) do
			setWheelShapeProps(wheel.node, wheel.wheelShape, 0, self.motor.brakeForce, 0);
		end;
		self:onDeactivateAttachements();
	end;
end;

IgnitionEvent = {};
IgnitionEvent_mt = Class(IgnitionEvent, Event);

InitEventClass(IgnitionEvent, "IgnitionEvent");

function IgnitionEvent:emptyNew()
    local self = Event:new(IgnitionEvent_mt);
    self.className="IgnitionEvent";
    return self;
end;

function IgnitionEvent:new(vehicle, ignition)
    local self = IgnitionEvent:emptyNew()
    self.vehicle = vehicle;
	self.ignition = ignition;
    return self;
end;

function IgnitionEvent:readStream(streamId, connection)
    local id = streamReadInt32(streamId);
	self.ignition = streamReadInt8(streamId);
    self.vehicle = networkGetObject(id);
    self:run(connection);
end;

function IgnitionEvent:writeStream(streamId, connection)
    streamWriteInt32(streamId, networkGetObjectId(self.vehicle));
	streamWriteInt8(streamId, self.ignition);
end;

function IgnitionEvent:run(connection)
	self.vehicle:setIgnition(self.ignition, true);
	if not connection:getIsServer() then
		g_server:broadcastEvent(IgnitionEvent:new(self.vehicle, self.ignition), nil, connection, self.object);
	end;
end;

function IgnitionEvent.sendEvent(vehicle, ignition, noEventSend)
	if noEventSend == nil or noEventSend == false then
		if g_server ~= nil then
			g_server:broadcastEvent(IgnitionEvent:new(vehicle, ignition), nil, nil, vehicle);
		else
			g_client:getServerConnection():sendEvent(IgnitionEvent:new(vehicle, ignition));
		end;
	end;
end;
