--
-- 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.aiMotorSound#pitchOffset"), 0);
        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;
	
	-- 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.batteryLightActive = false;
	self.fuelLightActive = false;
	self.ignitionMode = 0;	
    self.isMotorStarted = false;
	self.keySwitchR	= false;
	self.kluczyk1 = false;
	self.wskazowki	= false;
	self.kluczyk = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.kluczyk#index"));
    self.przycisk = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.przycisk#index"));	
	self.wskazowka1 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.wskazowka1#index"));		
    self.wskazowka2 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.wskazowka2#index"));
    self.wskazowka3 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.wskazowka3#index"));			
	self.keySwitch = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.keySwitch#index"));
    self.keyMinRot = 0;
    self.keyMaxRot = -40;
    self.keyRot = 0;
    self.rotSpeed = 0.1;
	
	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;
    self.printWarningTime = 0;
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;
	  end;
			if InputBinding.isPressed(InputBinding.IGNITIONMODE) and self.ignitionMode == 2 then
				setTranslation(self.przycisk, 0, Utils.degToRad(-0.5), 0);
				else		
				setTranslation(self.przycisk, 0, Utils.degToRad(0), 0);
			end;
			if InputBinding.isPressed(InputBinding.Warning) and self.ignitionMode == 0 then
			self.printWarningTime = self.time + 700;
		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.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
              self.keyRot = math.max(self.keyRot - self.rotSpeed*dt, self.keyMaxRot)
           end;
           if not self.keySwitchR then
           self.keyRot = math.min(self.keyRot + self.rotSpeed*dt, self.keyMinRot)
          end;
          setRotation(self.keySwitch, 0, Utils.degToRad(self.keyRot), 0);
		if self.kluczyk1 then
			setTranslation(self.kluczyk, 0, Utils.degToRad(-0.5), 0);
		end;
		if not self.kluczyk1 then
			setTranslation(self.kluczyk, 0, Utils.degToRad(0), 0);
		end;
		if self.wskazowki then
			setRotation(self.wskazowka1, 0, Utils.degToRad(-153), 0);
			setRotation(self.wskazowka2, 0, Utils.degToRad(-60), 0);
			setRotation(self.wskazowka3, 0, Utils.degToRad(-153), 0);
		end;
		if not self.wskazowki then
			setRotation(self.wskazowka1, 0, Utils.degToRad(0), 0);
			setRotation(self.wskazowka2, 0, Utils.degToRad(0), 0);
			setRotation(self.wskazowka3, 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()
    if self.isClient then
		if self.printWarningTime > self.time then
			g_currentMission:addWarning(g_i18n:getText("Odpalanie"));
		end;
	end;
end;

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

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

	self.keySwitchR = false;
    self.kluczyk1 = false;
    self.wskazowki = 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.ignitionKey = false;
		self.allowedIgnition = false;  
		self.isMotorStarted = false;
		self.keySwitchR = false;
		self.kluczyk1 = false;
		self.wskazowki = false;
	end;
	if self.ignitionMode == 1 then
		self.batteryLightActive = true;
		self.ignitionKey = false;
		self.allowedIgnition = false;  
		self.isMotorStarted = false;
		self.keySwitchR = true;
		self.kluczyk1 = true;
		self.wskazowki = false;
	end;
	if self.ignitionMode == 2 then
		self.batteryLightActive = false;
		self.allowedIgnition = true;
		self.ignitionKey = true;
		self.keySwitchR = true;
		self.kluczyk1 = true;
		self.wskazowki = 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;

