--
-- ManitoumanualIgnition
-- Specialization for manual Motor Ignition
--
-- @author  Templaer
-- @date  01/05/09
--
-- Modifikationen erst nach Rücksprache
-- Do not edit without my permission
--

ManitoumanualIgnition = {};

function ManitoumanualIgnition.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Motorized, specializations);
end;

function ManitoumanualIgnition: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.aiMotorSoundPitchOffset = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.motorSoundRun#pitchOffset"), 0);
        self.aiMotorSoundRadius = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.motorSoundRun#radius"), 50);
        self.aiMotorSoundInnerRadius = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.motorSoundRun#innerRadius"), 10);
        self.aiMotorSoundVolume = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.motorSoundRun#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;
	
	-- Backup Stop Sound volume
    self.motorStopSoundVolume2 = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.motorStopSound#volume"), 1.0);

	self.setIgnition = SpecializationUtil.callSpecializationsFunction("setIgnition");
	
	self.dashLights = {};
	self.dashLights[1] = Utils.indexToObject(self.components,getXMLString(xmlFile,"vehicle.dashLights#index1"));
	self.dashLights[2] = Utils.indexToObject(self.components,getXMLString(xmlFile,"vehicle.dashLights#index2"));
	self.dashLights[3] = Utils.indexToObject(self.components,getXMLString(xmlFile,"vehicle.dashLights#index3"));
	
	self.batteryLightActive = false;
	self.oilLightActive = false;
	self.fuelLightActive = false;
	self.ignitionMode = 0;	
    self.isMotorStarted = 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.numFuelLights = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.fuelLights#count"), 0);
    self.fuelLights = {};
    for i=1, self.numFuelLights do
        local fuelLightsNamei = string.format("vehicle.fuelLights.fuelLight" .. "%d", i);
        self.fuelLights[i] = Utils.indexToObject(self.rootNode, getXMLInt(xmlFile, fuelLightsNamei .. "#index"));
        setVisibility(self.fuelLights[i], false);
    end;
	

	local rotationPartNode13 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.rotationPart13#index"));
    if rotationPartNode13 ~= nil then
        self.rotationPart13 = {};
        self.rotationPart13.node = rotationPartNode13;

        local x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.rotationPart13#minRot"));
        self.rotationPart13.minRot = {};
        self.rotationPart13.minRot[1] = Utils.degToRad(Utils.getNoNil(x, 0));
        self.rotationPart13.minRot[2] = Utils.degToRad(Utils.getNoNil(y, 0));
        self.rotationPart13.minRot[3] = Utils.degToRad(Utils.getNoNil(z, 0));

        x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.rotationPart13#maxRot"));
        self.rotationPart13.maxRot = {};
        self.rotationPart13.maxRot[1] = Utils.degToRad(Utils.getNoNil(x, 0));
        self.rotationPart13.maxRot[2] = Utils.degToRad(Utils.getNoNil(y, 0));
        self.rotationPart13.maxRot[3] = Utils.degToRad(Utils.getNoNil(z, 0));

        self.rotationPart13.rotTime = Utils.getNoNil(getXMLString(xmlFile, "vehicle.rotationPart13#rotTime"), 2)*1000;
        self.rotationPart13.touchRotLimit = Utils.degToRad(Utils.getNoNil(getXMLString(xmlFile, "vehicle.rotationPart13#touchRotLimit"), 10));
    end;
end;

function ManitoumanualIgnition:delete()
end;

function ManitoumanualIgnition:readStream(streamId, connection)
	self:setIgnition(streamReadInt8(streamId), true);
end;

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

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

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

function ManitoumanualIgnition:update(dt)

	if self:getIsActiveForInput() then
		
			if InputBinding.hasEvent(InputBinding.IGNITIONMODE) then
				if self.ignitionMode > 2 then
					self.ignitionMode = 0;
				end;
				self:setIgnition(math.abs(self.ignitionMode + 1));

			end;
			if InputBinding.isPressed(InputBinding.IGNITIONMODE) and self.ignitionMode == 2 then
				setRotation(self.keySwitch1, 0, Utils.degToRad(-20), 0);
				else		
				setRotation(self.keySwitch1, 0, Utils.degToRad(0), 0);
			end;
	  end;
end;

function ManitoumanualIgnition: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:getIsActiveForInput() then
   
			
			-- Turn on the engine when pressing the accelerator

	    end;
		
	    -- Mutes stop sound when engine is off
	    if not self.ignitionKey or not self.deactivateOnLeave then
	        self.motorStopSoundVolume = 0;
        else
	        self.motorStopSoundVolume = self.motorStopSoundVolume2;
	    end;
								
        if self.ignitionKey and self.allowedIgnition then	
		    self:startMotor(true);
			self.allowedIgnition = false;
			self.deactivateOnLeave = false;
			self.steeringEnabled = true;
			Utils.setEmittingState(self.exhaustParticleSystems, true)
		elseif not self.ignitionKey and self.allowedIgnition then
		    if self.motorStopSoundVolume == 0 then
			    self.motorStopSoundVolume = self.motorStopSoundVolume2;
			end;
			
			self:stopMotor(true);
			self.allowedIgnition = false;
	        self.steeringEnabled = 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;
		
    -- 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;
	
	local fuelWarning = 0.2*self.fuelCapacity;
    if self.fuelFillLevel < fuelWarning then
	self.fuelLightActive = true;
	else
	self.fuelLightActive = false;	
    end;
    if self.fuelFillLevel == 0 then
    self.ignitionKey = false;
	self.fuelLightActive = false;
	self:stopMotor(true);
	self.allowedIgnition = false;
	self.steeringEnabled = 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.dashLights[1], self.batteryLightActive);
 	setVisibility(self.dashLights[2], self.oilLightActive);
 	setVisibility(self.dashLights[3], self.fuelLightActive);
	
		local maxfuelguage = 205;
			if self.rotationPart13 ~= nil then
				local x, y, z = getRotation(self.rotationPart13.node);
				y = ((self.rotationPart13.maxRot[2] - self.rotationPart13.minRot[2]) / maxfuelguage) * self.fuelFillLevel + self.rotationPart13.minRot[2];
				setRotation(self.rotationPart13.node, x, y ,z);
			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;
end;

function ManitoumanualIgnition:onLeave()
    if not self.deactivateOnLeave then
	    Utils.setEmittingState(self.exhaustParticleSystems, true)
		self.allowedIgnition = false;
		self.isMotorStarted = true;
		self.ignitionKey = true; 
		self.steeringEnabled = false;
		setVisibility(self.aiMotorSound, true);
		
		-- 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.isMotorStarted = false;
		self.ignitionKey = false;
		self.keySwitchR	= false;
	end;	
end;

function ManitoumanualIgnition:onEnter()
	-- Prevents the engine from starting upon entering
	if not self.ignitionKey then
		self.isMotorStarted = false;
		Motorized.stopSounds(self);
		self.steeringEnabled = false;
		Utils.setEmittingState(self.exhaustParticleSystems, false)
	else
	    self.steeringEnabled = true;
	end;
	
    setVisibility(self.aiMotorSound, false);
end;

function ManitoumanualIgnition:draw()
end;

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

	self.ignitionMode = ignition;
    self.ignitionKey = false;

	self.keySwitchR = false;
	self:stopMotor(true);
	self.allowedIgnition = false;
	self.steeringEnabled = 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.isMotorStarted = false;
		self.keySwitchR = false;
	end;
	if self.ignitionMode == 1 then
		self.batteryLightActive = true;
		self.oilLightActive = true;
		self.ignitionKey = false;
		self.allowedIgnition = false;  
		self.isMotorStarted = false;
		self.keySwitchR = true;
	end;
	if self.ignitionMode == 2 then
		self.batteryLightActive = false;
		self.allowedIgnition = true;
		self.oilLightActive = false;
		self.ignitionKey = true;
		self.keySwitchR = true;
	end;
	if self.ignitionMode > 2 then
		self.ignitionMode = 0;
	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;

