--
-- LemkenGigant1400
-- Specialization for LemkenGigant1400
--
-- @author  Felix S. - Outlaw
-- @date  01/05/09
-- @web www.ls-modsource.de - www.ls-mods.de
--
-- Copyright (C) Outlaw, All Rights Reserved.
--
-- @LS11 - Script Edit: Jegge
-- @date  26/11/106
--

LemkenGigant1400 = {};

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

function LemkenGigant1400:load(xmlFile)

    self.aiTerrainDetailChannel1 = g_currentMission.ploughChannel;
    self.aiTerrainDetailChannel2 = g_currentMission.sowingChannel;
    self.cultivatorLimitToField = true;

	self.connectCollisions = SpecializationUtil.callSpecializationsFunction("connectCollisions");
	self.anim = SpecializationUtil.callSpecializationsFunction("anim");
	self.Go = {}; 
	self.Done = {};
	self.charId = {};
	self.clipIndex = {};
	self.CheckDone = {};
	self.moveColli = {}; 
    self.animParts = {}
	self.collisionArm = {}; 
	local count = getXMLInt(xmlFile, "vehicle.animParts#count");
	local part = self.animParts;
    for i=1, count do
		part[i] = {};
        local partname = string.format("vehicle.animParts.part".."%d", i);
	    local nameR = getXMLString(xmlFile, partname.."#name");
		self.charId[nameR] = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, partname.."#rootNode"));
		self.clipIndex[nameR] = getXMLString(xmlFile, partname.."#animationClip");
		self.CheckDone[nameR] = false;
		self.moveColli[nameR] = getXMLString(xmlFile, partname.."#moveColli");
		if self.moveColli[nameR] ~= nil then
			local Collision = {};
			Collision.collision = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, partname.."#collision"));
			Collision.collisionAttacher = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, partname.."#collsionAttacher"));
			Collision.armAttacher = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, partname.. "#armAttacher"));
			Collision.index = 0;
			self.collisionArm[nameR] = Collision;
			self:connectCollisions(nameR);
		end; 
	end; 	
	
	if g_settingsJoystickEnabled then 
		self.keySet = not self.keySet;
	end; 	
	
	self.AIon = false;
	self.vehicleType = getXMLString(xmlFile, "vehicle#type");	
	
	local workSound = getXMLString(xmlFile, "vehicle.workSound#file");
    if workSound ~= nil and workSound ~= "" then
        workSound = Utils.getFilename(workSound, self.baseDirectory); 
        self.workSound = createSample("workSound");
        self.workSoundEnabled = false;
        loadSample(self.workSound, workSound, false);
        self.workSoundPitchOffset = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.workSound#pitchOffset"), 1);
        self.workSoundVolume = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.workSound#volume"), 1);
    end;
		
    self.dustParticleSystems = {};
    local dustParticleSystemCount = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.dustParticleSystems#count"), 0);
    for i=1, dustParticleSystemCount do
        local namei = string.format("vehicle.dustParticleSystems.part%d", i);
		local nodei = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, namei .. "#index"));
        Utils.loadParticleSystem(xmlFile, self.dustParticleSystems, namei, nodei, false, nil, self.baseDirectory)
    end;	
	
	local numSpinnerParts = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.SpinnerParts#count"), 0);
    self.SpinnerParts = {};
    for i=1, numSpinnerParts do
		local partnamei = string.format("vehicle.SpinnerParts.part" .. "%d", i);
		self.SpinnerParts[i] = {};
		self.SpinnerParts[i].index = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, partnamei .. "#index"));
		self.SpinnerParts[i].Scale = Utils.getNoNil(getXMLInt(xmlFile, partnamei .. "#rotScale"), 10);
    end;
	
	
	self.rotationSpeed = 0;
	self.rotationSpeedDownRate = 0;
	self.lastMovingDirection = 0;
	
    	
	self.rundumleuchten = {};
    self.rundumleuchten.rotNode = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.rundumleuchten#rotNode"));
    self.rundumleuchten.light = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.rundumleuchten#light"));
    self.rundumleuchten.source = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.rundumleuchten#lightsource"));
    self.rundumleuchten.speed = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.rundumleuchten#rotSpeed"), 1)/1000;
	self.rundumleuchtenAn = false;
	
	self.leftwheel = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.supportWheels#left"));
	self.rightwheel = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.supportWheels#right"));
    
	
	self.dy = 5000; 
	self.saveAILM = self.aiLeftMarker;
	self.aiLeftMarker = nil; 
	
end;


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

    if self:getIsActiveForInput() and InputBinding.isPressed(InputBinding.LemkenGigant1400_Beacon) and self.AIon == false then
        self.rundumleuchtenAn = not self.rundumleuchtenAn;
        setVisibility(self.rundumleuchten.light, self.rundumleuchtenAn);
    end;
	
	if self:getIsActiveForInput() and InputBinding.isPressed(InputBinding.LemkenGigant1400_Transport) and self.CheckDone.back == false and self.AIon == false and not self.Go.back then
		self.Go.trsp = not self.Go.trsp; 
		self.Done.trsp = true; 
    end;
	
	if self:getIsActiveForInput() and InputBinding.isPressed(InputBinding.LemkenGigant1400_lower) and self.CheckDone.trsp == true and self.AIon == false and self.Go.trsp then
		self.Go.senken = not self.Go.senken; 
		self.Done.senken = true; 
    end;
		
end;


function LemkenGigant1400:update(dt)

	if self.attacherVehicle then

		if self.keySet then
			self.keyType = InputBinding.getKeyNamesOfDigitalAction;
			self.keyName = "Button"; 
		else
			self.keyType = InputBinding.getKeyNamesOfDigitalAction;
			self.keyName = "Taste"; 
		end; 
		
		if self.Go.trsp ~= nil and self.Done.trsp ~= false then
			self:anim("trsp", false); 
		end;
		
		if self.Go.back ~= nil and self.Done.back ~= false then
			self:anim("back", false); 
		end;
		
		if self.Go.senken ~= nil and self.Done.senken ~= false then
			self:anim("senken", false); 
		end;
		if self:getIsActiveForInput() then
		if InputBinding.hasEvent(InputBinding.IMPLEMENT_EXTRA) then
		self.cultivatorLimitToField = not self.cultivatorLimitToField
		end
		end
	
				
		if self.rundumleuchtenAn ~= false then
			rotate(self.rundumleuchten.rotNode, 0, dt*self.rundumleuchten.speed, 0);
		end;
		
		if self.attacherVehicle.isAITractorActivated ~= nil then
			self.AIon = self.attacherVehicle.isAITractorActivated;
		end; 	

		if self.delay == true then
	        self.dy = self.dy - dt;
	        if self.dy <= 0 then
	            self.delay = false;
	            self.dy = 5000; 
				self.Go.senken = not self.Go.senken; 
				self.Done.senken = true; 
	        end;
	    end;
		
		if self.CheckDone.trsp then
			local x,y,z = getRotation(self.wheels[1].repr);	
			setRotation(self.leftwheel, x, y, z);
			setRotation(self.rightwheel, x, y, z);			
		end; 
		
		
		if self.CheckDone.senken and self.blockb == nil then
			self.blockb = true;
			self.Go.back = not self.Go.back; 
			self.Done.back = true; 
		end;

		if self.CheckDone.senken == false and self.blockb then
			self.blockb = nil;
			self.Go.back = not self.Go.back; 
			self.Done.back = true; 
		end; 	
			
		if self.CheckDone.back and self:getIsAreaActive(cuttingArea3) then
			local x,y,z = getWorldTranslation(self.cuttingAreas[3].start);
			local x1,y1,z1 = getWorldTranslation(self.cuttingAreas[3].width);
			local x2,y2,z2 = getWorldTranslation(self.cuttingAreas[3].height);
			Utils.updateCultivatorArea(x, z, x1, z1, x2, z2, not self.cultivatorLimitToField);

		end;
			if self.cultivatorLimitToField then
			local limitToField = self.cultivatorLimitToField;

		end;
		 
		
		if self.CheckDone.senken == false and self.AIon == false and self.attacherVehicle.isAITractorActivated ~= nil then
			self.aiLeftMarker = nil; 
			AITractor.updateToolsInfo(self.attacherVehicle)
		end; 
		
		if self.CheckDone.senken == true then
			if self.CheckDone.back and self.attacherVehicle.isAITractorActivated ~= nil then 
				self.aiLeftMarker = self.saveAILM; 
				AITractor.updateToolsInfo(self.attacherVehicle)
			end;
		 	
			if self.CheckDone.senken and self:getIsAreaActive(cuttingArea1) then
			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);
			Utils.updateCultivatorArea(x, z, x1, z1, x2, z2, not self.cultivatorLimitToField);

		end;
			if self.cultivatorLimitToField then
			local limitToField = self.cultivatorLimitToField;
		end;

			if self.CheckDone.senken and self:getIsAreaActive(cuttingArea2) 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);
			Utils.updateCultivatorArea(x, z, x1, z1, x2, z2, not self.cultivatorLimitToField);

		end;
			if self.cultivatorLimitToField then
			local limitToField = self.cultivatorLimitToField;
		end;

			
			self.rotationSpeed = self.attacherVehicle.lastSpeed * self.attacherVehicle.movingDirection;
			self.rotationSpeedDownRate = math.abs(self.rotationSpeed * 0.02);
			self.lastMovingDirection = self.attacherVehicle.movingDirection;
			self.rotationSpeed = self.rotationSpeed - self.rotationSpeedDownRate;
			local rotS = self.rotationSpeed * 1000; 
			if rotS == 0 then
				self.rotationSpeed = 0;
				Utils.setEmittingState(self.dustParticleSystems, false)
				if self.workSoundEnabled then
					stopSample(self.workSound);
					self.workSoundEnabled = nil;
				end;
			else
				Utils.setEmittingState(self.dustParticleSystems, true)
				if not self.workSoundEnabled and not self.AIon then
					setSamplePitch(self.workSound, self.workSoundPitchOffset);
					playSample(self.workSound, 0, self.workSoundVolume, 0);
					self.workSoundEnabled = true;
				end;
			end; 	
			for i=1, table.getn(self.SpinnerParts) do
				rotate(self.SpinnerParts[i].index , self.SpinnerParts[i].Scale * self.rotationSpeed ,0,0);
			end;
		else
			if self.workSoundEnabled then
				stopSample(self.workSound);
				self.workSoundEnabled = nil;
			end;
			Utils.setEmittingState(self.dustParticleSystems, false)
		end; 	
		
	end; 
	
	if self.Go.pillar ~= nil and self.Done.pillar ~= false then
		self:anim("pillar", false); 
	end; 
	
end;


function LemkenGigant1400:onAttach()
	self.Go.pillar = not self.Go.pillar; 
	self.Done.pillar = true; 
end; 


function LemkenGigant1400:onDetach()
	self.Go.pillar = not self.Go.pillar; 
	self.Done.pillar = true;
	Utils.setEmittingState(self.dustParticleSystems, false)
	if self.workSoundEnabled then
		stopSample(self.workSound);
		self.workSoundEnabled = nil;
	end;
end;	


function LemkenGigant1400:draw()		
	
	if self.AIon == false then
		if self.rundumleuchtenAn then
			g_currentMission:addHelpButtonText(string.format(g_i18n:getText(self.vehicleType..".2"), self.typeDesc),InputBinding.LemkenGigant1400_Beacon);
		else
			g_currentMission:addHelpButtonText(string.format(g_i18n:getText(self.vehicleType..".1"), self.typeDesc),InputBinding.LemkenGigant1400_Beacon);
		end;
		
		if self.CheckDone.back == false then
			if self.Go.trsp then
				g_currentMission:addHelpButtonText(string.format(g_i18n:getText(self.vehicleType..".3"), self.typeDesc),InputBinding.LemkenGigant1400_Transport);
			else
				g_currentMission:addHelpButtonText(string.format(g_i18n:getText(self.vehicleType..".4"), self.typeDesc),InputBinding.LemkenGigant1400_Transport);
			end;
		end; 		
		
		if self.CheckDone.trsp and self.Go.trsp then
			if self.Go.senken then
				g_currentMission:addHelpButtonText(string.format(g_i18n:getText(self.vehicleType..".6"), self.typeDesc),InputBinding.LemkenGigant1400_lower);
			else
				g_currentMission:addHelpButtonText(string.format(g_i18n:getText(self.vehicleType..".5"), self.typeDesc),InputBinding.LemkenGigant1400_lower);
			end; 
		end; 	
	end;

end;


function LemkenGigant1400:delete()
	removeJoint(self.collisionArm.pillar.index); 
	Utils.setEmittingState(self.dustParticleSystems, false)
	if self.workSoundEnabled then
		stopSample(self.workSound);
		self.workSoundEnabled = nil;
	end;	
end;


function LemkenGigant1400:anim(varName, loopCheck)
	if self.moveColli[varName] ~= nil then
		local Collision = self.collisionArm[varName];
		setJointFrame(Collision.index, 0, Collision.armAttacher);
	end;
	if self.Go[varName] == true and self.Done[varName] ~= false then
		local charId = getAnimCharacterSet(self.charId[varName]);
		local clipIndex = getAnimClipIndex(charId, self.clipIndex[varName]);
		assignAnimTrackClip(charId , 0, clipIndex);
		setAnimTrackLoopState(charId, 0, loopCheck);
		setAnimTrackSpeedScale(charId, 0, 1);
		enableAnimTrack(charId, 0);
		if getAnimTrackTime(charId, 0) >= getAnimClipDuration(charId, clipIndex) and loopCheck == false then
			disableAnimTrack(charId, 0);	
			self.Done[varName] = false;	
			self.CheckDone[varName] = true;	
		end; 
	elseif self.Go[varName] == false and self.Done[varName] ~= false then
		local charId = getAnimCharacterSet(self.charId[varName]);
		local clipIndex = getAnimClipIndex(charId, self.clipIndex[varName]);
		if loopCheck == true then
			disableAnimTrack(charId, 0);
			self.Done[varName] = false;	
		end; 	
		assignAnimTrackClip(charId , 0, clipIndex);
		setAnimTrackLoopState(charId, 0, loopCheck);
		setAnimTrackSpeedScale(charId, 0, -1);
		enableAnimTrack(charId, 0);
		if getAnimTrackTime(charId, 0) <= 0 then
			disableAnimTrack(charId, 0);
			self.Done[varName] = false;	
			self.CheckDone[varName] = false;
		end;
	end;
end; 


function LemkenGigant1400:connectCollisions(varName)
	local Collision = self.collisionArm[varName];
	local constr = JointConstructor:new();
	constr:setActors(self.rootNode, Collision.collision);
	constr:setJointTransforms(Collision.armAttacher, Collision.collisionAttacher);
	for i=1, 3 do		            
		constr:setRotationLimit(i-1, 0, 0, 0);
		constr:setTranslationLimit(i-1, true, 0, 0);
	end;
	Collision.index = constr:finalize();
end;


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


function LemkenGigant1400:aiLower()
	--[[if self.CheckDone.senken == false then
		self.delay = true;
	end;]]
	self.Go.senken = not self.Go.senken; 
	self.Done.senken = true; 
end; 


function LemkenGigant1400:aiRaise()
	self.Go.senken = not self.Go.senken; 
	self.Done.senken = true; 
end;