--
-- PUN for Niva CK 5M
-- by Northern_Strike(RUS) for LSSA 
-- http://www.lsmods-rus.com & http://lssa.ru/
-- 13.12.11 
-- 

source("dataS/scripts/vehicles/specializations/SetTurnedOnEvent.lua");
nivapun = {};

function nivapun.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Trailer, specializations);
end;

function nivapun:load(xmlFile)

	self.drawMirror = false;

    self.mirrors = {};
    self.mirrors[1] = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.mirrors.mirror1#index"));
	
    self.setIsTurnedOn = SpecializationUtil.callSpecializationsFunction("setIsTurnedOn");
    self.fillScale = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.fillScale#value"), 1);
    self.wasToFast = false;
    self.isTurnedOn = false;
	self.currentFruitType = FruitUtil.FRUITTYPE_UNKNOWN;
	
	self.lastArea = 0;
	self.lastAreaBiggerZero = self.lastArea > 0;

	self.pipeChaffParticleSystems = {};
    local i = 0;
    while true do
        local namei = string.format("vehicle.pipeChaffParticleSystems.pipeChaffParticleSystem(%d)", i);
		local nodei = Utils.indexToObject(self.components, getXMLString(xmlFile, namei .. "#index"));
		if nodei == nil then
			break;
		end; 
        Utils.loadParticleSystem(xmlFile, self.pipeChaffParticleSystems, namei, nodei, false, nil, self.baseDirectory)		
		Utils.setEmittingState(self.pipeChaffParticleSystems,false)
		i = i +1;		
    end;
	
	self.pipeStrawParticleSystems = {};
    local i = 0;
    while true do
        local namei = string.format("vehicle.pipeStrawParticleSystems.pipeStrawParticleSystem(%d)", i);
		local nodei = Utils.indexToObject(self.components, getXMLString(xmlFile, namei .. "#index"));
		if nodei == nil then
			break;
		end; 
        Utils.loadParticleSystem(xmlFile, self.pipeStrawParticleSystems, namei, nodei, false, nil, self.baseDirectory)		
		Utils.setEmittingState(self.pipeStrawParticleSystems,false)
		i = i +1;		
    end;
	
	self.currentPS = self.pipeChaffParticleSystems;

	self.trailerRaycastCallback = nivapun.trailerRaycastCallback;

	self.pipe = {};
	self.pipe.node = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.pipe#index"));
	self.pipe.distance = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.pipe#raycastDistance"), 7);

	self.isLoading = true;

end;

function nivapun:delete()
end;

function nivapun:readStream(streamId, connection)
    local turnedOn = streamReadBool(streamId);
    self:setIsTurnedOn(turnedOn, true);
	self.isLoading = true;
	self.lastAreaBiggerZero = streamReadBool(streamId);
	self.currentFruitType = streamReadInt8(streamId);
end;

function nivapun:writeStream(streamId, connection)
    streamWriteBool(streamId, self.isTurnedOn);
	streamWriteBool(streamId, self.lastAreaBiggerZero);
	streamWriteInt8(streamId, self.currentFruitType);
    streamWriteBool(streamId, self.isLoaded);
end;

function nivapun:readUpdateStream(streamId, timestamp, connection)
	if connection:getIsServer() then
		self.lastAreaBiggerZero = streamReadBool(streamId);
		self.currentFruitType = streamReadInt8(streamId);
	end;
end;

function nivapun:writeUpdateStream(streamId, connection, dirtyMask)
	if not connection:getIsServer() then
		streamWriteBool(streamId, self.lastAreaBiggerZero);
		streamWriteInt8(streamId, self.currentFruitType);
	end;
end;

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

function nivapun:keyEvent(unicode, sym, modifier, isDown)

end;

function nivapun:update(dt)

		setVisibility(self.mirrors[1], self.drawMirror);

        if self.nivapunActive then
            self:setIsTurnedOn(not self.isTurnedOn);
        end;
 
 	if self.setAnimationTime ~= nil then
		if self.nivapunActive then
			self:setAnimationTime(1, 1);
		else
			self:setAnimationTime(1, 0);
		end;
	end;
 
end;

function nivapun:updateTick(dt)

				  if self.attacherVehicle ~= nil then
                      isAllowed = self.attacherVehicle:getIshreshingAllowed(false);
                  end;

			if isAllowed then
				if self.attacherVehicle ~= nil then
					if self.attacherVehicle.isThreshing then
						self.nivapunActive = true;
					else
						self.nivapunActive = false;
					end;
				end;
			end;
					
	self.trailerFoundId = 0;
    self.wasToFast = false;
    self.lastArea = 0;

	local x, y, z = getWorldTranslation(self.pipe.node);
	local dx, dy, dz = localDirectionToWorld(self.pipe.node, 0, -0.5, 0);
	raycastAll(x, y, z, dx, dy, dz, "trailerRaycastCallback", self.pipe.distance, self);
			
    if self:getIsActive() then
		local deltaLevel = 0;

        if self.nivapunActive and self.attacherVehicle.nivapunActive1 then
            local toFast = self:doCheckSpeedLimit() and self.attacherVehicle.lastSpeed*3600 > 29;
							self.currentFruitType = FruitUtil.fillTypeToFruitType[fillType];
								Utils.setEmittingState(self.pipeStrawParticleSystems, true);
							local deltaLevel = 10;
							if self.trailerFoundId ~= nil and self.trailerFoundId ~= 0 then
								local trailer = g_currentMission.nodeToVehicle[self.trailerFoundId];
								if trailer ~= nil and trailer ~= self and trailer:allowFillType(Fillable.FILLTYPE_CHAFF, true) and trailer.allowFillFromAir and trailer.capacity ~= trailer.fillLevel then
									trailer:setFillLevel(trailer.fillLevel+deltaLevel, Fillable.FILLTYPE_CHAFF);
								end;
							end;
		else
			Utils.setEmittingState(self.pipeStrawParticleSystems, false);
        end;
    end;
end;

function nivapun:draw()

end;

function nivapun:onDetach()
	self.nivapunActive = false;
if self.attacherVehicle then
  end;
	Utils.setEmittingState(self.pipeChaffParticleSystems, false);
	Utils.setEmittingState(self.pipeStrawParticleSystems, false);
    if self.deactivateOnDetach then
        nivapun.onDeactivate(self);
    else
    end;
	self.drawMirror = false;
end;

function nivapun:onAttach()
	self.drawMirror = true;
end;

function nivapun:onLeave()

end;

function nivapun:onDeactivate()
	Utils.setEmittingState(self.pipeChaffParticleSystems, false);
	Utils.setEmittingState(self.pipeStrawParticleSystems, false);
end;

function nivapun:setIsTurnedOn(turnedOn, noEventSend)
    SetTurnedOnEvent.sendEvent(self, turnedOn, noEventSend)
    self.isTurnedOn = turnedOn;
end;

function nivapun:trailerRaycastCallback(transformId, x, y, z, distance)
	local vehicle = g_currentMission.nodeToVehicle[transformId];
	if vehicle ~= nil then
		if vehicle.exactFillRootNode == transformId then
			self.trailerFoundId = transformId;
			return false;
		end;
	end;
	return true;
end;