--
-- JF92Z10

-- Author  Sandro_ADM
-- MAD date  27.05.2011
--
-- > farming simulator 2011 < --

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

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

function JF92Z10:load(xmlFile)


	local count = getXMLInt(xmlFile, "vehicle.rotationParts#count");
         self.rotationParts = {}
	local rotationPart = self.rotationParts;
         for i=1, count do
	local varName = string.format("rotationPart" .. "%d", i);
	rotationPart[varName] = {};
        local rotationPartname = string.format("vehicle.rotationParts.rotationPart" .. "%d", i);
	rotationPart[varName].index = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, rotationPartname .. "#index"));
        local x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, rotationPartname .. "#minRot"));
	    rotationPart[varName].minRot = {};
	    rotationPart[varName].minRot[1] = Utils.degToRad(Utils.getNoNil(x, 0));
	    rotationPart[varName].minRot[2] = Utils.degToRad(Utils.getNoNil(y, 0));
	    rotationPart[varName].minRot[3] = Utils.degToRad(Utils.getNoNil(z, 0));
	local x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, rotationPartname .. "#maxRot"));
	    rotationPart[varName].maxRot = {};
	    rotationPart[varName].maxRot[1] = Utils.degToRad(Utils.getNoNil(x, 0));
	    rotationPart[varName].maxRot[2] = Utils.degToRad(Utils.getNoNil(y, 0));
	    rotationPart[varName].maxRot[3] = Utils.degToRad(Utils.getNoNil(z, 0));
	    rotationPart[varName].rotTime = Utils.getNoNil(getXMLInt(xmlFile, rotationPartname .. "#rotTime"), 2)*1000;	
	    rotationPart[varName].touchRotLimit = Utils.getNoNil(getXMLInt(xmlFile, rotationPartname .. "#touchRotLimit"), 1)/1000;	
        end;




    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.polia = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.polia#index"));
	self.rotor1 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.rotor1#index"));
	self.rotor2 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.rotor2#index"));

	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 = JF92Z10.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 JF92Z10:delete()
end;

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

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

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

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

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

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

function JF92Z10:update(dt)
    if self:getIsActiveForInput() then
        if InputBinding.hasEvent(InputBinding.JF92Z10_TurnOn) then
            self:setIsTurnedOn(not self.isTurnedOn);
        end;
		if InputBinding.isPressed(InputBinding.JF92Z10_PipeDown) and self:getIsActiveForInput() then
			self:setAnimationTime(1, self.animationParts[1].currentPosition+(self.animationParts[1].offSet+dt), false);
		elseif InputBinding.isPressed(InputBinding.JF92Z10_PipeUp) and self:getIsActiveForInput() then
			self:setAnimationTime(1, self.animationParts[1].currentPosition-(self.animationParts[1].offSet+dt), false);
		end;
    end;
end;

function JF92Z10: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
			rotate(self.polia, 0,-1.8, 0);
			rotate(self.rotor1, 0, 1.8, 0);
			rotate(self.rotor2, 0, 0, 1.8);
		end;
        if self.isTurnedOn then
            local toFast = self:doCheckSpeedLimit() and self.attacherVehicle.lastSpeed*3600 > 15;
            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;


        if self.isTurnedOn then	
					
		if InputBinding.isPressed(InputBinding.JF92Z10YPIPERIGHT) then
			local rotationPart = self.rotationParts.rotationPart1;
			local rot = {getRotation(rotationPart.index)};
			local newRot = Utils.getMovedLimitedValues(rot, rotationPart.maxRot, rotationPart.minRot, 3, rotationPart.rotTime, dt, true);
			setRotation(rotationPart.index, unpack(newRot));
	    end;		
		if InputBinding.isPressed(InputBinding.JF92Z10YPIPELEFT) then
			local rotationPart = self.rotationParts.rotationPart1;
			local rot = {getRotation(rotationPart.index)};
			local newRot = Utils.getMovedLimitedValues(rot, rotationPart.maxRot, rotationPart.minRot, 3, rotationPart.rotTime, dt, false);
			setRotation(rotationPart.index, unpack(newRot));
	    end;  
		if InputBinding.isPressed(InputBinding.JF92Z10KLAPPEDOWN) then
			local rotationPart = self.rotationParts.rotationPart2;
			local rot = {getRotation(rotationPart.index)};
			local newRot = Utils.getMovedLimitedValues(rot, rotationPart.maxRot, rotationPart.minRot, 3, rotationPart.rotTime, dt, true);
			setRotation(rotationPart.index, unpack(newRot));
	    end;
		if InputBinding.isPressed(InputBinding.JF92Z10KLAPPEUP) then
			local rotationPart = self.rotationParts.rotationPart2;
			local rot = {getRotation(rotationPart.index)};
			local newRot = Utils.getMovedLimitedValues(rot, rotationPart.maxRot, rotationPart.minRot, 3, rotationPart.rotTime, dt, false);
			setRotation(rotationPart.index, unpack(newRot));		
		end;
		

		local rotationPart = self.rotationParts.rotationPart1;
		local rotationPart = self.rotationParts.rotationPart2;
		local xr,yr,zr = getRotation(rotationPart.index);
		local zl = 7 * math.cos(xr)

	end;


		
end;

function JF92Z10: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.JF92Z10_TurnOn);
    else
        g_currentMission:addHelpButtonText(string.format(g_i18n:getText("turn_on_OBJECT"), self.typeDesc), InputBinding.JF92Z10_TurnOn);
    end;

end;

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

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

function JF92Z10: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 JF92Z10:setIsTurnedOn(turnedOn, noEventSend)
    SetTurnedOnEvent.sendEvent(self, turnedOn, noEventSend)
    self.isTurnedOn = turnedOn;
end;

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