--
-- AmazoneUX5200
-- Specialization for AmazoneUX5200
--
-- @author Felix "Outlaw" Sorge
-- @date  19/06/09
-- @web www.ls-modsource.de - www.ls-mods.de
--
-- Copyright (C) Outlaw, All Rights Reserved.
--

AmazoneUX5200 = {};

function AmazoneUX5200.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Fillable, specializations);
end;

function AmazoneUX5200:load(xmlFile)

	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 = {};
	self.startpoint = {};
	self.loopCheck = {};
	self.Speed = {};


	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.components, getXMLString(xmlFile, partname.."#rootNode"));
		self.clipIndex[nameR] = getXMLString(xmlFile, partname.."#animationClip");
		self.CheckDone[nameR] = false;
		self.moveColli[nameR] = getXMLString(xmlFile, partname.."#moveColli");
		self.startpoint[nameR] = Utils.getNoNil(getXMLFloat(xmlFile, partname.."#startpoint"),0.0);
		if self.moveColli[nameR] ~= nil then
			local Collision = {};
			Collision.collision = Utils.indexToObject(self.components, getXMLString(xmlFile, partname.."#collision"));
			Collision.collisionAttacher = Utils.indexToObject(self.components, getXMLString(xmlFile, partname.."#collsionAttacher"));
			Collision.armAttacher = Utils.indexToObject(self.components, getXMLString(xmlFile, partname.. "#armAttacher"));
			Collision.index = 0;
			self.collisionArm[nameR] = Collision;
			self:connectCollisions(nameR);
		end; 
	local numWorkLights = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.workLights#count"), 0);
    self.workLights = {};
    for i=1, numWorkLights do
        local worklightnamei = string.format("vehicle.workLights.workLight%d", i);
        self.workLights[i] = Utils.indexToObject(self.components, getXMLString(xmlFile, worklightnamei .. "#index"));
        setVisibility(self.workLights[i], false);
    end;
	self.workLightsActive = false;

	local numwezes = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.wezes#count"), 0);
    self.wezes = {};
    for i=1, numwezes do
        local wezenamei = string.format("vehicle.wezes.weze%d", i);
        self.wezes[i] = Utils.indexToObject(self.components, getXMLString(xmlFile, wezenamei .. "#index"));
        setVisibility(self.wezes[i], false);
    end;
	self.wezesActive = false;

	local charId = getAnimCharacterSet(self.charId[nameR]);
		local clipIndex = getAnimClipIndex(charId, self.clipIndex[nameR]);
		assignAnimTrackClip(charId , 0, clipIndex);
		setAnimTrackTime(charId, 0, self.startpoint[nameR]);
		enableAnimTrack(charId, 0);
		disableAnimTrack(charId, 0);
		self.loopCheck[nameR] = false;
		self.Speed[nameR] = 1.0;
	end; 
			
	local nummarkAreas = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.markAreas#count"), 0);
    self.markAreas = {}
    for i=1, nummarkAreas do
        self.markAreas[i] = {};
        local areanamei = string.format("vehicle.markAreas.markAreas%d", i);
        self.markAreas[i].point = Utils.indexToObject(self.components, getXMLString(xmlFile, areanamei .. "#pointIndex"));
        self.markAreas[i].width = Utils.getNoNil(getXMLFloat(xmlFile, areanamei .. "#width"), 0.5)
        self.markAreas[i].height = Utils.getNoNil(getXMLFloat(xmlFile, areanamei .. "#height"), 0.25)
    end;
	
	self.sprayParticleSystems = {};
    local i = 0;
    while true do
        local namei = string.format("vehicle.sprayParticleSystems.sprayParticleSystems(%d)", i);
		local nodei = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, namei .. "#index"));
		if nodei == nil then
			break;
		end; 
        Utils.loadParticleSystem(xmlFile, self.sprayParticleSystems, namei, nodei, false, nil, self.baseDirectory)		
		i = i +1;		
    end;
	
	local spraySound = getXMLString(xmlFile, "vehicle.spraySound#file");
    if spraySound ~= nil and spraySound ~= "" then
        spraySound = Utils.getFilename(spraySound, self.baseDirectory);
        self.spraySound = createSample("spraySound");
        self.spraySoundEnabled = false;
        loadSample(self.spraySound, spraySound, false);
        self.spraySoundPitchOffset = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.spraySound#pitchOffset"), 1);
        self.spraySoundVolume = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.spraySound#volume"), 1);
    end;
	
	local hydraulicSound = getXMLString(xmlFile, "vehicle.hydraulicSound#file");
    if hydraulicSound ~= nil and hydraulicSound ~= "" then
        hydraulicSound = Utils.getFilename(hydraulicSound, self.baseDirectory);
        self.hydraulicSound = createSample("hydraulicSound");
        self.hydraulicSoundEnabled = false;
        loadSample(self.hydraulicSound, hydraulicSound, false);
        self.hydraulicSoundPitchOffset = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.hydraulicSound#pitchOffset"), 1);
        self.hydraulicSoundVolume = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.hydraulicSound#volume"), 1);
    end;
	
	self.exParticleSystems = {};
    local i = 0;
    while true do
        local namei = string.format("vehicle.exParticleSystems.exParticleSystems(%d)", i);
		local nodei = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, namei .. "#index"));
		if nodei == nil then
			break;
		end; 
        Utils.loadParticleSystem(xmlFile, self.exParticleSystems, namei, nodei, false, nil, self.baseDirectory)		
		i = i +1;		
    end;
	self.backuplm = self.aiLeftMarker;
	self.backuprm = self.aiRightMarker;

    self.aiTerrainDetailChannel1 = g_currentMission.ploughChannel;
    self.aiTerrainDetailChannel2 = g_currentMission.sowingChannel;
	self.AIon = false;
	
	self.saveAILM = self.aiLeftMarker;
	self.aiLeftMarker = nil; 	
	
    self.attacherBackup = nil;
    self.TurnRadiusBackup = 0;	
	
	self.groundCheck = {};
	self.groundCheck.left = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.groundCheck#left"));
	self.groundCheck.right = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.groundCheck#right"));
	
	self.literPerHa = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.literPerHa#value"), 1);
	
	self.keyType = InputBinding.getButtonKeyName;
	self.keyName = "Taste"; 
	setMass(self.rootNode, 1.5);
end;


function AmazoneUX5200:update(dt)
	setMass(self.rootNode, 1.5);
	
		
	if self.attacherVehicle and self:getIsActiveForInput()then
	
		if InputBinding.isPressed(InputBinding.AmazoneUX5200_AI) then
		self.reload = true;
		else
		self.reload = false;
	    end;
		if InputBinding.hasEvent(InputBinding.AmazoneUX5200_RSM) then
			self.wezesActive = not self.wezesActive;
	    end;
	if self.reload then
		if not self.aiLeftMarker then
				self.aiLeftMarker = self.backuplm;
			end; 			
		if not self.aiRightMarker then
				self.aiRightMarker = self.backuprm;
		end; 
	end;
	end;

	if self.attacherVehicle then
	
	

	if self.attacherVehicle.isAITractorActivated ~= nil then
			self.AIon = self.attacherVehicle.isAITractorActivated;
		end; 
		
		if  self.attacherVehicle.isAITractorActivated ~= nil then 
			self.aiLeftMarker = self.saveAILM; 
			AITractor.updateToolsInfo(self.attacherVehicle)
		end; 			
		
		if self.AIon then
		self.attacherVehicle.steeringAxleAngle = 0;
		end;
		
		if self.attacherBackup == nil and self.attacherVehicle ~= nil then
            self.attacherBackup = self.attacherVehicle;
        end;
		if self:getIsActiveForInput() and InputBinding.hasEvent(InputBinding.AmazoneUX5200_transport) and not self.turnOn and not self.levelCheck then
			self.Speed.trsp = 1.0; 
			self.Speed.ex = 1.0; 
			self.Go.trsp = not self.Go.trsp; 
			self.Done.trsp = true;  
			self.Go.hubmast = false; 
			self.Done.hubmast = true;
			if self.exSave then
				self.Go.ex = not self.Go.ex;
				self.Done.ex = true;
			end; 
		end; 
		
		for k, weze in pairs(self.wezes) do
			setVisibility(weze, self.wezesActive);
		end;
		for k, worklight in pairs(self.workLights) do
			setVisibility(worklight, self.workLightsActive);
		end;

		if self:getIsActiveForInput() and InputBinding.hasEvent(InputBinding.AmazoneUX5200_on) and self.CheckDone.trsp and self.fillLevel ~= 0 and self.Go.trsp then
			self.turnOn = not self.turnOn; 
		end; 
		
		if self:getIsActiveForInput() and InputBinding.hasEvent(InputBinding.AmazoneUX5200_ex) and self.CheckDone.trsp and self.Go.trsp then
			self.Speed.ex = 1.0; 
			self.Go.ex = not self.Go.ex; 
			self.Done.ex = true;  
			self.exSave = not self.exSave; 
		end; 
		
		if self:getIsActiveForInput() and InputBinding.hasEvent(InputBinding.AmazoneUX5200_mark) and not self.CheckDone.trsp and not self.Go.trsp then
			self.markOn = not self.markOn;
		end;
		
		if self:getIsActiveForInput() and InputBinding.hasEvent(InputBinding.AmazoneUX5200_levelcheck) and self.CheckDone.trsp and self.Go.trsp then
			self.levelCheck = not self.levelCheck; 
		end;
				
		if self:getIsActiveForInput() and InputBinding.isPressed(InputBinding.AmazoneUX5200_up) and not self.levelCheck and self.CheckDone.trsp and self.Go.trsp then
			self.Go.hubmast = true; 
			self.Done.hubmast = true;
		
		elseif self:getIsActiveForInput() and InputBinding.isPressed(InputBinding.AmazoneUX5200_down) and not self.levelCheck and self.CheckDone.trsp and self.Go.trsp then
			self.Go.hubmast = false; 
			self.Done.hubmast = true;
		elseif not self.Done.trsp and not self.levelCheck and self.CheckDone.trsp and self.Go.trsp then
			self.Done.hubmast = false; 
		end; 
		
		if self.Done.trsp then
			if not self.hydraulicSoundEnabled and self:getIsActiveForSound() then
	            playSample(self.hydraulicSound, 0, self.hydraulicSoundVolume, 0);
	            setSamplePitch(self.hydraulicSound, self.hydraulicSoundPitchOffset);
	            self.hydraulicSoundEnabled = true;
	        end;
		else
			if self.hydraulicSoundEnabled then
		        stopSample(self.hydraulicSound);
		        self.hydraulicSoundEnabled = false;
			end;
		end; 	
		
		if self.levelCheck then	
			local x,y,z = getWorldTranslation(self.groundCheck.right);
			local terrainHeight = getTerrainHeightAtWorldPos(g_currentMission.terrainRootNode, x, 0, z);
			local gCr = y-terrainHeight; 
			local x,y,z = getWorldTranslation(self.groundCheck.left);
			local terrainHeight = getTerrainHeightAtWorldPos(g_currentMission.terrainRootNode, x, 0, z);
			local gCl = y-terrainHeight; 
			local gC = math.floor(math.min(gCl,gCr) * 10) / 10;
			if (gC < 2.0) then 
				self.Go.hubmast = false; 
				self.Done.hubmast = true;
			else
				self.Go.hubmast = true; 
				self.Done.hubmast = true;
			end;
		end; 		
				
		
		if self.fillLevel == 0 then
		    if self.spraySoundEnabled then
		        stopSample(self.spraySound);
		        self.spraySoundEnabled = false;
			end;
			Utils.setEmittingState(self.sprayParticleSystems, false)
			Utils.setEmittingState(self.exParticleSystems, false)
			self.turnOn = false; 
			self.aiLeftMarker = nil; 
			self.aiRightMarker = nil;
		end; 
		
		if self.turnOn then
			local difficultyMultiplier = math.max(3 * (3 - g_currentMission.missionStats.difficulty), 1);
			local usage = self.literPerHa*0.000065*(self.attacherVehicle.lastSpeed*3600);
			self:setFillLevel(self.fillLevel-usage, self.currentFillType);
			
			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 not self.spraySoundEnabled and self:getIsActiveForSound() then
	            playSample(self.spraySound, 0, self.spraySoundVolume, 0);
	            setSamplePitch(self.spraySound, self.spraySoundPitchOffset);
	            self.spraySoundEnabled = true;
	        end;
			
			if self.wezesActive then
				Utils.setEmittingState(self.sprayParticleSystems, false)
				Utils.setEmittingState(self.exParticleSystems, false)
				if self.CheckDone.ex and self.Go.ex and not self.Done.ex 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);
				end; 
			else
				Utils.setEmittingState(self.sprayParticleSystems, true)			
				if self.CheckDone.ex and self.Go.ex and not self.Done.ex then
				Utils.setEmittingState(self.exParticleSystems, true)
				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);
				end; 
			
				if not self.Go.ex then
					Utils.setEmittingState(self.exParticleSystems, false)
				end; 
			end;
			
		else
			Utils.setEmittingState(self.sprayParticleSystems, false)
			Utils.setEmittingState(self.exParticleSystems, false)
			if self.spraySoundEnabled then
		        stopSample(self.spraySound);
		        self.spraySoundEnabled = false;
			end;
		end; 	
	end; 	
		
		
	if self.markOn then		
		for k, markAreas in pairs(self.markAreas) do
	        local x,y,z = getWorldTranslation(markAreas.point);
	        local w = markAreas.width;
	        local h = markAreas.height;
			local x1 = x + h/2
			local x2 = x - h/2
			local z1 = z + w/2
			local z2 = z - w/2			
			Utils.cutFruitArea( 1, x1, z2, x1, z1, x2, z2);
			Utils.cutFruitArea( 2, x1, z2, x1, z1, x2, z2);
			Utils.cutFruitArea( 3, x1, z2, x1, z1, x2, z2);
			Utils.cutFruitArea( 4, x1, z2, x1, z1, x2, z2);
			Utils.updateMeadowArea(x1, z2, x1, z1, x2, z2);
			Utils.updateCuttedMeadowArea(x1, z2, x1, z1, x2, z2);
		end;
	end; 
	
	if self.Go.pillar ~= nil and self.Done.pillar ~= false then
		self:anim("pillar", false); 
	end; 
	
	if self.Go.trsp ~= nil and self.Done.trsp ~= false then
		self:anim("trsp", false); 
	end;

	self:anim("hubmast", false); 

	if self.Go.ex ~= nil and self.Done.ex ~= false then
		self:anim("ex", false); 
	end;
	
end;

function AmazoneUX5200:draw()
end;

function AmazoneUX5200:anim(varName, loopCheck)
	if self.moveColli[varName] ~= nil then
		local Collision = self.collisionArm[varName];
		setJointFrame(Collision.index, 0, Collision.armAttacher);
	end;
	local loopCheck = self.loopCheck[varName];
	local speed = Utils.getNoNil(self.Speed[varName],1);
	local offset = 10;  
	local charId = getAnimCharacterSet(self.charId[varName]);
	local clipIndex = getAnimClipIndex(charId, self.clipIndex[varName]);
	if self.Done[varName] ~= false then
		if self.Go[varName] == true then
			assignAnimTrackClip(charId , 0, clipIndex);
			setAnimTrackLoopState(charId, 0, loopCheck);
			setAnimTrackSpeedScale(charId, 0, speed);
			enableAnimTrack(charId, 0);
			if getAnimTrackTime(charId, 0) >= getAnimClipDuration(charId, clipIndex) and loopCheck == false then
				self.Done[varName] = false;	
				self.CheckDone[varName] = self.Go[varName];	
			end;
			if getAnimTrackTime(charId, 0) >= getAnimClipDuration(charId, clipIndex) and loopCheck then
				local setTime = getAnimClipDuration(charId, clipIndex) - getAnimClipDuration(charId, clipIndex);
				setAnimTrackTime(charId, 0, setTime);
			end;
		elseif self.Go[varName] == false then
			if loopCheck == true then
				self.Done[varName] = false;	
			else
				assignAnimTrackClip(charId , 0, clipIndex);
				setAnimTrackLoopState(charId, 0, loopCheck);
				setAnimTrackSpeedScale(charId, 0, -speed);
				enableAnimTrack(charId, 0);
				if getAnimTrackTime(charId, 0) <= 0 then
					self.Done[varName] = false;	
					self.CheckDone[varName] = self.Go[varName];
				end;
			end;
		elseif self.Go[varName] ~= nil then
			assignAnimTrackClip(charId , 0, clipIndex);
			setAnimTrackLoopState(charId, 0, loopCheck);
			if self.Go[varName] < 0.0 then
				self.Go[varName] = 0.0;
			elseif self.Go[varName] > getAnimClipDuration(charId, clipIndex) then
				self.Go[varName] = getAnimClipDuration(charId, clipIndex);
			end;
			if getAnimTrackTime(charId, 0) >= self.Go[varName] then
				setAnimTrackSpeedScale(charId, 0, -speed);
			else
				setAnimTrackSpeedScale(charId, 0, speed);
			end;
			enableAnimTrack(charId, 0);
			if getAnimTrackTime(charId, 0) <= self.Go[varName] + offset and getAnimTrackTime(charId, 0) >= self.Go[varName] - offset then
				self.Done[varName] = false;	
				self.CheckDone[varName] = self.Go[varName];
			end;
		end;
	end;
	if self.Done[varName] == false then
		disableAnimTrack(charId, 0);
	end;
end; 

function AmazoneUX5200: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 AmazoneUX5200:mouseEvent(posX, posY, isDown, isUp, button)
end;

function AmazoneUX5200:keyEvent(unicode, sym, modifier, isDown)
	if isDown and sym==Input.KEY_8 then
		self.keySet = not self.keySet; 
		if self.keySet then
			self.keyType = InputBinding.getButtonName;
			self.keyName = "Button"; 
		else
			self.keyType = InputBinding.getButtonKeyName;
			self.keyName = "Taste"; 
		end; 
	end;
	if isDown and sym == Input.KEY_z then
			self.workLightsActive = not self.workLightsActive;
	end;
end;

function AmazoneUX5200:onAttach()
	self.Go.pillar = not self.Go.pillar; 
	self.Done.pillar = true; 
    self.TurnRadiusBackup = self.attacherVehicle.aiTractorTurnRadius;
    self.attacherVehicle.aiTractorTurnRadius = 0;
end; 	

function AmazoneUX5200:onDetach()
	self.Go.pillar = not self.Go.pillar; 
	self.Done.pillar = true; 
	self.turnOn = false; 
	if self.spraySoundEnabled then
		stopSample(self.spraySound);
		self.spraySoundEnabled = false;
	end;
	if self.hydraulicSoundEnabled then
		stopSample(self.hydraulicSound);
		self.hydraulicSoundEnabled = false;
	end;
	 self.attacherBackup.aiTractorTurnRadius = self.TurnRadiusBackup;
     self.attacherVehicle = self.attacherBackup;
     self.attacherVehicle = nil;
     self.attacherBackup = nil;
end;

function AmazoneUX5200:delete()
	Utils.setEmittingState(self.sprayParticleSystems, false)
	Utils.setEmittingState(self.exParticleSystems, false)
	if self.hydraulicSoundEnabled then
		stopSample(self.hydraulicSound);
		self.hydraulicSoundEnabled = false;
	end;
	if self.spraySoundEnabled then
		stopSample(self.spraySound);
		self.spraySoundEnabled = false;
	end;
	for k, worklight in pairs(self.workLights) do
		setVisibility(worklight, false);
	end;
	self.workLightsActive = false;
	for k, weze in pairs(self.wezes) do
		setVisibility(weze, false);
	end;
end;

function AmazoneUX5200:getSaveAttributesAndNodes(nodeIdent)
	local attributes = 'trsp="'..tostring(self.CheckDone.trsp)..'" mark="'..tostring(self.markOn)..'" ex="'..tostring(self.exSave)..'" weze="'..tostring(self.wezesActive)..'"';
	return attributes, nil;
end;

function AmazoneUX5200:loadFromAttributesAndNodes(xmlFile, key, resetVehicles)
	local trsp = getXMLBool(xmlFile, key.."#trsp");
	if trsp and not resetVehicles then
		self.Go.trsp = not self.Go.trsp; 
		self.Done.trsp = true; 
		self.Speed.trsp = 100.0;
	end; 
	
	local ex = getXMLBool(xmlFile, key.."#ex");
	if ex and not resetVehicles then
		self.exSave = true; 
		if trsp then
			self.Go.ex = not self.Go.ex; 
			self.Done.ex = true; 
			self.Speed.ex = 100.0;
		end; 
	end; 
	
	local mark = getXMLBool(xmlFile, key.."#mark");
	if mark and not resetVehicles then
		self.markOn = true; 
	end; 

	local weze = getXMLBool(xmlFile, key.."#weze");
	if weze and not resetVehicles then
		self.wezesActive = true; 
	end; 
	
	
    return BaseMission.VEHICLE_LOAD_OK;
end;

function AmazoneUX5200:aiLower()
self.turnOn = true;
end; 


function AmazoneUX5200:aiRaise()
self.turnOn = false;
				self.aiLeftMarker = nil; 
				self.aiRightMarker = nil;
end; 	
