-- Vaderstad TopDown cultivator
-- by psycho


Vaderstad_TopDown = {};

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

function Vaderstad_TopDown:load(xmlFile)
            print("'lua loaded '" );	
self.safeMode = true
	self.dungArea = SpecializationUtil.callSpecializationsFunction("dungArea");
	self.foliageManureId = getChild(g_currentMission.terrainRootNode, "grass");

	self.setParticleState = SpecializationUtil.callSpecializationsFunction("setParticleState");

	self.aiTerrainDetailChannel1 = g_currentMission.sowingChannel; 
	self.aiTerrainDetailChannel2 = g_currentMission.cultivatorChannel; 
	self.AIon=false;
	
	self.siewnik1 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.siewnik1#index"));
	self.siewnik2 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.siewnik2#index"));
	self.siewnik3 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.siewnik3#index"));
	
	self.particleSystems = {};
	local particleSystemCount = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.ParticleSystems#count"), 0);
	for i = 1, particleSystemCount do
		local namei = string.format("vehicle.ParticleSystems.ParticleSystem%d", i);
		self.particleSystems[i] = {};
		self.particleSystems[i].ps = {};
		self.particleSystems[i].node = {};
		self.particleSystems[i].rain = {};
		self.particleSystems[i].node = Utils.indexToObject(self.components, getXMLString(xmlFile, namei .. "#node"));
		self.particleSystems[i].rain = Utils.getNoNil(getXMLBool(xmlFile, namei .. "#deactivateOnRain"), false);
		Utils.loadParticleSystem(xmlFile, self.particleSystems[i].ps, namei, self.components, false, nil, self.baseDirectory);
	end;
	self.particleState = false;

    self.speedRotatingParts = {};
    local i=0;
    while true do
        local baseName = string.format("vehicle.speedRotatingParts.speedRotatingPart(%d)", i);
        local index = getXMLString(xmlFile, baseName.. "#index");
        if index == nil then
            break;
        end;
        local node = Utils.indexToObject(self.components, index);
        if node ~= nil then
            local entry = {};
            entry.node = node;
            entry.rotationSpeedScale = getXMLFloat(xmlFile, baseName.."#rotationSpeedScale");
            if entry.rotationSpeedScale == nil then
                entry.rotationSpeedScale = 1.0/Utils.getNoNil(getXMLFloat(xmlFile, baseName.."#radius"), 1);
            end;

            entry.foldMinLimit = Utils.getNoNil(getXMLFloat(xmlFile, baseName .. "#foldMinLimit"), 0);
            entry.foldMaxLimit = Utils.getNoNil(getXMLFloat(xmlFile, baseName .. "#foldMaxLimit"), 1);

            table.insert(self.speedRotatingParts, entry);
        end;
        i = i+1;
    end;
   
	
	local rotationPartNodeRight = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.rotationPartRight#index"));
    if rotationPartNodeRight ~= nil then
        self.rotationPartRight = {};
        self.rotationPartRight.node = rotationPartNodeRight;

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

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

        self.rotationPartRight.rotTime = Utils.getNoNil(getXMLString(xmlFile, "vehicle.rotationPartRight#rotTime"), 100)*1000;
        self.rotationPartRight.touchRotLimit = Utils.degToRad(Utils.getNoNil(getXMLString(xmlFile, "vehicle.rotationPartRight#touchRotLimit"), 10));
    end;
	
	
	local rotationPartNodeLeft = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.rotationPartLeft#index"));
    if rotationPartNodeLeft ~= nil then
        self.rotationPartLeft = {};
        self.rotationPartLeft.node = rotationPartNodeLeft;

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

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

        self.rotationPartLeft.rotTime = Utils.getNoNil(getXMLString(xmlFile, "vehicle.rotationPartLeft#rotTime"), 100)*1000;
        self.rotationPartLeft.touchRotLimit = Utils.degToRad(Utils.getNoNil(getXMLString(xmlFile, "vehicle.rotationPartLeft#touchRotLimit"), 10));
    end;
	
	
	local translationPartNode = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.translationPart#index"));
    if translationPartNode ~= nil then
        self.translationPart = {};
        self.translationPart.node = translationPartNode;
        local x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.translationPart#minTrans"));
        self.translationPart.minTrans = {};
        self.translationPart.minTrans[1] = Utils.getNoNil(x, 0);
        self.translationPart.minTrans[2] = Utils.getNoNil(y, 0);
        self.translationPart.minTrans[3] = Utils.getNoNil(z, 0);

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

        self.translationPart.transTime = Utils.getNoNil(getXMLString(xmlFile, "vehicle.translationPart#transTime"), 2)*1000;
        self.translationPart.touchTransLimit = Utils.getNoNil(getXMLString(xmlFile, "vehicle.translationPart#touchTransLimit"), 10);
    end;
	
	local translationPartNode2 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.translationPart2#index"));
    if translationPartNode2 ~= nil then
        self.translationPart2 = {};
        self.translationPart2.node = translationPartNode2;
        local x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.translationPart2#minTrans"));
        self.translationPart2.minTrans = {};
        self.translationPart2.minTrans[1] = Utils.getNoNil(x, 0);
        self.translationPart2.minTrans[2] = Utils.getNoNil(y, 0);
        self.translationPart2.minTrans[3] = Utils.getNoNil(z, 0);

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

        self.translationPart2.transTime = Utils.getNoNil(getXMLString(xmlFile, "vehicle.translationPart2#transTime"), 2)*1000;
        self.translationPart2.touchTransLimit = Utils.getNoNil(getXMLString(xmlFile, "vehicle.translationPart2#touchTransLimit"), 10);
    end;
	
	self.rotationMaxRight = true;
	self.rotationMaxLeft = true;
	self.translationMax2 = false;
	self.translationMax =  false;
end;

function Vaderstad_TopDown:delete()
	for k, v in pairs(self.particleSystems) do
		Utils.deleteParticleSystem(v.ps);
	end;
end;


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

function Vaderstad_TopDown:keyEvent(unicode, sym, modifier, isDown)
	
	if isDown and sym == Input.KEY_x then
	self.rozlozony = not self.rozlozony;
	end;
	
	if isDown and sym == Input.KEY_v then
		self.translationMax2 = not self.translationMax2;
	end;
	
	if isDown and sym == Input.KEY_z then
	self.poplon = not self.poplon;
	end;

end;


function Vaderstad_TopDown:update(dt)
	
if self.attacherVehicle then
if self:getIsActiveForInput() then
		if InputBinding.hasEvent (InputBinding.IMPLEMENT_EXTRA) then 
		self.safeMode = not self.safeMode 
		end;

		if self.poplon then
					setVisibility(self.siewnik1, true);
					setVisibility(self.siewnik2, true);
					setVisibility(self.siewnik3, true);
		else
					setVisibility(self.siewnik1, false);
					setVisibility(self.siewnik2, false);
					setVisibility(self.siewnik3, false);
		end;
		
		if self.rozlozony then
		self.rotationMaxRight = true;
		self.rotationMaxLeft = true;
		else
		self.rotationMaxRight = false
		self.rotationMaxLeft = false;
		end
end;
		if self.attacherVehicle.isAITractorActivated ~= nil then
			self.AIon = self.attacherVehicle.isAITractorActivated;	
		end; 



								


	if self.attacherVehicle.isAITractorActivated then				
    	self.attacherVehicle.turnStage3Timeout = 0;
		
			if self.attacherVehicle.turnStage == 0 then
		self.translationMax2 = true;
			
			else
		self.translationMax2 = false;
			end;
	else
		
		if self.attacherVehicle.isAITractorActivated ~= nil then
			self.attacherVehicle.turnStage3Timeout = 35000;
		end; 	
	end;
end;

 ----script-----
 	if self.attacherVehicle then
		if self.rotationPartRight ~= nil then
            local x, y, z = getRotation(self.rotationPartRight.node);
            local minRot = self.rotationPartRight.minRot;
            local eps = self.rotationPartRight.touchRotLimit;
        end;
		
		if self.translationMax2 and self.attacherVehicle.lastSpeed*3600 > 5 then			
				self:setParticleState(true);				
			else
				self:setParticleState(false);
		end;

		if self.translationMax2 then			
			if table.getn(self.cuttingAreas) > 0 then
				if self.poplon then
					local x,y,z = getWorldTranslation(self.cuttingAreas[2].start);
					local x1,y1,z1 = getWorldTranslation(self.cuttingAreas[2].width);
					local x2,y2,z2 = getWorldTranslation(self.cuttingAreas[2].height);
					self:dungArea(x, z, x1, z1, x2, z2);
				end;

				local x,y,z = getWorldTranslation(self.cuttingAreas[1].start);
				local x1,y1,z1 = getWorldTranslation(self.cuttingAreas[1].width);
				local x2,y2,z2 = getWorldTranslation(self.cuttingAreas[1].height);
						if self.safeMode then
							Vaderstad_TopDown.updateSafeArea (x, z, x1, z1, x2, z2) 
						else 
							Utils.updatePloughArea (x, z, x1, z1, x2, z2); 
						end;
				for k,v in pairs(self.speedRotatingParts) do
                    rotate(v.node, v.rotationSpeedScale * self.lastSpeedReal * self.movingDirection * dt, 0, 0);
				end;
			end;
		end;	
	
	
		
	local doTranslate = self.translationMax or self.translationMin
		if self.translationPart ~= nil and doTranslate then
	
        local x, y, z = getTranslation(self.translationPart.node);
        local trans = {x,y,z};
        local newTrans = Utils.getMovedLimitedValues(trans, self.translationPart.maxTrans, self.translationPart.minTrans, 3, self.translationPart.transTime, dt, not self.translationMax);
        setTranslation(self.translationPart.node, unpack(newTrans));
		end;

	if self.rotationPartRight ~= nil then
        local x, y, z = getRotation(self.rotationPartRight.node);
        local rot = {x,y,z};
        local newRot = Utils.getMovedLimitedValues(rot, self.rotationPartRight.maxRot, self.rotationPartRight.minRot, 3, self.rotationPartRight.rotTime, dt, not self.rotationMaxRight);
        setRotation(self.rotationPartRight.node, unpack(newRot));
    end;

    if self.rotationPartLeft ~= nil then
        local x, y, z = getRotation(self.rotationPartLeft.node);
        local rot = {x,y,z};
        local newRot = Utils.getMovedLimitedValues(rot, self.rotationPartLeft.maxRot, self.rotationPartLeft.minRot, 3, self.rotationPartLeft.rotTime, dt, not self.rotationMaxLeft);
        setRotation(self.rotationPartLeft.node, unpack(newRot));
    end;
	
	if self.translationMax2 ~= nil then
		local x, y, z = getTranslation(self.translationPart2.node);
        local trans = {x,y,z};
        local newTrans = Utils.getMovedLimitedValues(trans, self.translationPart2.maxTrans, self.translationPart2.minTrans, 3, self.translationPart2.transTime, dt, not self.translationMax2);
        setTranslation(self.translationPart2.node, unpack(newTrans));
	end;
	end;
end;

function Vaderstad_TopDown:setParticleState(state, noEventSend)
	for k, v in pairs(self.particleSystems) do
		if v.rain then
			if g_currentMission.environment.lastRainScale <= 0.1 and g_currentMission.environment.timeSinceLastRain > 40 then
				Utils.setEmittingState(v.ps, state);
			else
				Utils.setEmittingState(v.ps, false);
			end;
		else
			Utils.setEmittingState(v.ps, state);
		end;
	end;
	self.particleState = state;
end;

function Vaderstad_TopDown:draw()
end;

function Vaderstad_TopDown:onDetach()
		self.translationMin = false ;
		self.translationMax = true;
		
end;


function Vaderstad_TopDown:onAttach()
		self.translationMax = true ;
		self.translationMin = false ;
		
end; 
		
Vaderstad_TopDown.updateSafeArea = function(l_18_0, l_18_1, l_18_2, l_18_3, l_18_4, l_18_5)
  local cultiId = g_currentMission.cultivatorChannel
  local sowingId = g_currentMission.sowingChannel
  local detailId = g_currentMission.terrainDetailId
  local ploughId = g_currentMission.ploughChannel
  local sprayId = g_currentMission.sprayChannel
  local x, z, widthX, widthZ, heightX, heightZ = Utils.getXZWidthAndHeight(detailId, l_18_0, l_18_1, l_18_2, l_18_3, l_18_4, l_18_5)
  Utils.updateDestroyCommonArea(l_18_0, l_18_1, l_18_2, l_18_3, l_18_4, l_18_5)
  setDensityMaskedParallelogram(detailId, x, z, widthX, widthZ, heightX, heightZ, ploughId, 1, detailId, sowingId, 1, 1)
  setDensityMaskedParallelogram(detailId, x, z, widthX, widthZ, heightX, heightZ, ploughId, 1, detailId, cultiId, 1, 1)
  setDensityParallelogram(detailId, x, z, widthX, widthZ, heightX, heightZ, sowingId, 1, 0)
  setDensityParallelogram(detailId, x, z, widthX, widthZ, heightX, heightZ, cultiId, 1, 0)
  setDensityParallelogram(detailId, x, z, widthX, widthZ, heightX, heightZ, sprayId, 1, 0)
end;

function Vaderstad_TopDown:loadFromAttributesAndNodes(xmlFile, key, resetVehicles)  
  if not resetVehicles then
	local roboczy = getXMLBool(xmlFile, key.."#roboczy");
	if roboczy then
	   self.rozlozony = true;
	end;
 	local poplon = getXMLBool(xmlFile, key.."#poplon");
	if poplon then
	   self.poplon = true;
	end;
   return BaseMission.VEHICLE_LOAD_OK;
 end;
end;

function Vaderstad_TopDown:getSaveAttributesAndNodes(nodeIdent)
   local attributes = 'roboczy="'..tostring(self.rozlozony)..' "poplon="'..tostring(self.poplon)..'"';
   return attributes, nil;
end;

function Vaderstad_TopDown:dungArea(x, z, x1, z1, x2, z2)
	local cultiId = g_currentMission.cultivatorChannel;
	local sowingId = g_currentMission.sowingChannel;
	local detailId = g_currentMission.terrainDetailId;
	local ploughId = g_currentMission.ploughChannel;
	local sprayId = g_currentMission.sprayChannel;
	local dx, dz, dwidthX, dwidthZ, dheightX, dheightZ = Utils.getXZWidthAndHeight(detailId, x, z, x1, z1, x2, z2)
	setDensityMaskedParallelogram(self.foliageManureId, dx, dz, dwidthX, dwidthZ, dheightX, dheightZ, 0, 1, detailId, sowingId, 1, 1)
	setDensityMaskedParallelogram(self.foliageManureId, dx, dz, dwidthX, dwidthZ, dheightX, dheightZ, 0, 1, detailId, ploughId, 1, 1)
	setDensityMaskedParallelogram(self.foliageManureId, dx, dz, dwidthX, dwidthZ, dheightX, dheightZ, 0, 1, detailId, cultiId, 1, 1)
end;
