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


detk128 = {};

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

function detk128:load(xmlFile)
	self.lowerRmp = SpecializationUtil.callSpecializationsFunction("lowerRmp");
	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 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; 
	
	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 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.literPerSecond = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.literPerSecond#value"), 1);
		
	self.keyType = InputBinding.getButtonKeyName;
	self.keyName = "Taste"; 
end;


function detk128:update(dt)

	if self:getIsActive() then
		if InputBinding.hasEvent(InputBinding.detk128_on)  and self:getIsActiveForInput() then
			self.turnOn = not self.turnOn; 
		end; 
		
		if self.fillLevel == 0 then
			self.turnOn = false; 
			Utils.setEmittingState(self.dustParticleSystems, false)
			if self.workSoundEnabled then
		        stopSample(self.workSound);
		        self.workSoundEnabled = false;
			end;
			self:lowerRmp();
		end; 
		
		if self.turnOn then
			if not self.backupRmp then
				self.backupRmp = self.attacherVehicle.motor.minRpm;
			end; 			
			if self.attacherVehicle.motor.minRpm >= -500 then
				self.attacherVehicle.motor.minRpm = self.attacherVehicle.motor.minRpm - 10; 
			end; 		
			local difficultyMultiplier = math.max(3 * (3 - g_currentMission.missionStats.difficulty), 1);
			local deltaLevel = FruitUtil.fruitIndexToDesc[self.currentFillType].literPerQm * difficultyMultiplier * self.literPerSecond;
			self:setFillLevel(self.fillLevel-deltaLevel, self.currentFillType);
			Utils.setEmittingState(self.dustParticleSystems, true)
			for k,cuttingArea in pairs(self.cuttingAreas) do
                local x,y,z = getWorldTranslation(cuttingArea.start);
                local x1,y1,z1 = getWorldTranslation(cuttingArea.width);
                local x2,y2,z2 = getWorldTranslation(cuttingArea.height);
                Utils.updateSprayArea(x, z, x1, z1, x2, z2);
            end;
			if not self.workSoundEnabled and self:getIsActiveForSound() then
	            playSample(self.workSound, 0, self.workSoundVolume, 0);
	            setSamplePitch(self.workSound, self.workSoundPitchOffset);
	            self.workSoundEnabled = true;
	        end;	
		else
			Utils.setEmittingState(self.dustParticleSystems, false)
			if self.workSoundEnabled then
		        stopSample(self.workSound);
		        self.workSoundEnabled = false;
			end;
			self:lowerRmp();
		end;

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

function detk128:delete()
	Utils.setEmittingState(self.dustParticleSystems, false)
	if self.workSoundEnabled then
	    stopSample(self.workSound);
		self.workSoundEnabled = false;
	end;
	self:lowerRmp();
end;

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

function detk128: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; 
end;

function detk128:draw()
	if self.turnOn then
		g_currentMission:addExtraPrintText(self.keyName.. " " ..self.keyType(InputBinding.detk128_on).. ": " ..g_i18n:getText("detk128_2")); 
	else 
		g_currentMission:addExtraPrintText(self.keyName.. " " ..self.keyType(InputBinding.detk128_on).. ": " ..g_i18n:getText("detk128_1")); 
	end; 	
end;

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

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



function detk128: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 detk128: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 detk128:lowerRmp()
	if self.backupRmp and self.attacherVehicle then
		if self.attacherVehicle.motor.minRpm <= self.backupRmp then
			self.attacherVehicle.motor.minRpm = self.attacherVehicle.motor.minRpm + 10; 
		else
			self.attacherVehicle.motor.minRpm = self.backupRmp; 
			self.backupRmp = nil; 			
		end; 	
	end; 
end;