ClaasJaguar25 = {};

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

function ClaasJaguar25:load(xmlFile)
    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 = ClaasJaguar25.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 ClaasJaguar25:delete()
end;

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

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

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

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

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

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

function ClaasJaguar25:update(dt)
    if self:getIsActiveForInput() then
        if InputBinding.hasEvent(InputBinding.ClaasJaguar25_TurnOn) then
            self:setIsTurnedOn(not self.isTurnedOn);
        end;
		if InputBinding.isPressed(InputBinding.ClaasJaguar25_PipeRight) and self:getIsActiveForInput() then
			self:setAnimationTime(1, self.animationParts[1].currentPosition+(self.animationParts[1].offSet+dt), false);
		elseif InputBinding.isPressed(InputBinding.ClaasJaguar25_PipeLeft) and self:getIsActiveForInput() then
			self:setAnimationTime(1, self.animationParts[1].currentPosition-(self.animationParts[1].offSet+dt), false);
		end;
		
		if InputBinding.isPressed(InputBinding.ClaasJaguar25_PipeDown) and self:getIsActiveForInput() then
			self:setAnimationTime(2, self.animationParts[2].currentPosition+(self.animationParts[2].offSet+dt), false);
		elseif InputBinding.isPressed(InputBinding.ClaasJaguar25_PipeUp) and self:getIsActiveForInput() then
			self:setAnimationTime(2, self.animationParts[2].currentPosition-(self.animationParts[2].offSet+dt), false);
		end;
    end;
	
	if self.isTurnedOn then
		self:setAnimationTime(3, 1);
	else
		self:setAnimationTime(3, 0);
	end;
end;

function ClaasJaguar25:updateTick(dt)
	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.isTurnedOn then
            local toFast = self:doCheckSpeedLimit() and self.attacherVehicle.lastSpeed*3600 > 25;
            if self.isServer then
                if not toFast then
                    local cuttingAreasSend = {};
                    for k, cuttingArea in pairs(self.cuttingAreas) do
                        if self:getIsAreaActive(cuttingArea) then
                            local x,y,z = getWorldTranslation(cuttingArea.start);
                            local x1,y1,z1 = getWorldTranslation(cuttingArea.width);
                            local x2,y2,z2 = getWorldTranslation(cuttingArea.height);
                            table.insert(cuttingAreasSend, {x,z,x1,z1,x2,z2});
                        end;
                    end;
                    if (table.getn(cuttingAreasSend) > 0) then
						local lastArea, fillType = AreaEvent.runLocally(cuttingAreasSend, self.fillTypes, self.currentFillType);
						self.lastArea = lastArea;
						self.lastAreaBiggerZero = (self.lastArea > 0);
                        if lastArea > 0 then
							self.currentFruitType = FruitUtil.fillTypeToFruitType[fillType];
							if self.currentFruitType == FruitUtil.FRUITTYPE_GRASS or self.currentFruitType == FruitUtil.FRUITTYPE_DRYGRASS or self.currentFruitType == FruitUtil.FRUITTYPE_MAIZE then 
								self.currentPS = self.pipeChaffParticleSystems
							else
								self.currentPS = self.pipeStrawParticleSystems;
							end;
                            local pixelToSqm = g_currentMission:getFruitPixelsToSqm(); -- 4096px are mapped to 2048m
							literPerSqm = FruitUtil.fruitIndexToDesc[self.currentFruitType].literPerSqm;
                            local sqm = lastArea *pixelToSqm;
                            local deltaLevel = sqm*literPerSqm * self.fillScale;
							
							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;
							g_server:broadcastEvent(AreaEvent:new(cuttingAreasSend, fillType));
                        end;
                    end;
                end;
            end;
			Utils.setEmittingState(self.currentPS, self.lastAreaBiggerZero);
            self.wasToFast = toFast;
		else
			Utils.setEmittingState(self.pipeChaffParticleSystems, false);
			Utils.setEmittingState(self.pipeStrawParticleSystems, false);
        end;
    end;
end;

function ClaasJaguar25:draw()
    if self.wasToFast then
        g_currentMission:addWarning(g_i18n:getText("Dont_drive_to_fast") .. "\n" .. string.format(g_i18n:getText("Cruise_control_levelN"), "1", InputBinding.getKeyNamesOfDigitalAction(InputBinding.SPEED_LEVEL2)), 0.07+0.022, 0.019+0.015);
    end;

    if self.isTurnedOn then
        g_currentMission:addHelpButtonText(string.format(g_i18n:getText("turn_off_OBJECT"), self.typeDesc), InputBinding.ClaasJaguar25_TurnOn);
    else
        g_currentMission:addHelpButtonText(string.format(g_i18n:getText("turn_on_OBJECT"), self.typeDesc), InputBinding.ClaasJaguar25_TurnOn);
    end;
end;

function ClaasJaguar25:onDetach()
	Utils.setEmittingState(self.pipeChaffParticleSystems, false);
	Utils.setEmittingState(self.pipeStrawParticleSystems, false);
    if self.deactivateOnDetach then
        ClaasJaguar25.onDeactivate(self);
    else
    end;
end;

function ClaasJaguar25:onLeave()
	Utils.setEmittingState(self.pipeChaffParticleSystems, false);
	Utils.setEmittingState(self.pipeStrawParticleSystems, false);
    if self.deactivateOnLeave then
        ClaasJaguar25.onDeactivate(self);
    else
    end;
end;

function ClaasJaguar25:onDeactivate()
	Utils.setEmittingState(self.pipeChaffParticleSystems, false);
	Utils.setEmittingState(self.pipeStrawParticleSystems, false);
	if self.isTurnedOn then
		if self.activesound then
			stopSample(self.activesound);
			playSample(self.desligarotor, 1, 1, 0);
			self.ligarotorRunning = false;
		end;
		if self.attacherVehicle then
			stopSample(self.activesound);
			playSample(self.desligarotor, 1, 1, 0);
			self.ligarotorRunning = false;
		end;
	end;
    self.isTurnedOn = false;
end;

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

function ClaasJaguar25: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;