--
-- JDT660i Combine
-- Specialization for combine
--
-- @author  Bayn - www.tsforum3.com
-- @date  11/07/09
--

JDT660i = {};

function JDT660i.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Motorized, specializations);
end;

function JDT660i:load(xmlFile)
	
	
	------------------------------------------
	------ Keys ------------
	------------------------------------------


	self.keys = {};
    local i=0;
    while true do
        local baseName = string.format("vehicle.keys.input(%d)", i);
        local inputName = getXMLString(xmlFile, baseName.. "#name");
        if inputName == nil then
            break;
        end;
        local inputKey = getXMLString(xmlFile, baseName.. "#key");
        if Input[inputKey] == nil then
            print("Error: invalid key '" .. inputKey .. "'  for input event '" .. inputName .. "'");
            break;
        end;
        self.keys[inputName] = Input[inputKey];
        i = i+1;
    end;
	
	-- Animations from xml --
	
	
	self.anim = SpecializationUtil.callSpecializationsFunction("anim");
  	self.charId = {};
	self.clipIndex = {};
	self.Go = {}; 
	self.Done = {};
	self.CheckDone = {};
	local count = getXMLInt(xmlFile, "vehicle.animParts#count");
    self.animParts = {}
	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;
		

	end;   
  
  -- Steering Wheel movements --
	
	local rotationNodeColonne = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.rotationColonne#index"));
    if rotationNodeColonne ~= nil then
        self.rotationColonne = {};
        self.rotationColonne.node = rotationNodeColonne;
        local x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.rotationColonne#minRot"));
        self.rotationColonne.minRot = {};
        self.rotationColonne.minRot[1] = Utils.degToRad(Utils.getNoNil(x, 0));
        self.rotationColonne.minRot[2] = Utils.degToRad(Utils.getNoNil(y, 0));
        self.rotationColonne.minRot[3] = Utils.degToRad(Utils.getNoNil(z, 0));

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

        self.rotationColonne.rotTime = Utils.getNoNil(getXMLString(xmlFile, "vehicle.rotationColonne#rotTime"), 2)*1000;
        self.rotationColonne.touchRotLimit = Utils.degToRad(Utils.getNoNil(getXMLString(xmlFile, "vehicle.rotationColonne#touchRotLimit"), 10));
    end; 

	-- Ladder movements --
	
	local rotationNodeEchelle = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.rotationEchelle#index"));
    if rotationNodeEchelle ~= nil then
        self.rotationEchelle = {};
        self.rotationEchelle.node = rotationNodeEchelle;
        local x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.rotationEchelle#minRot"));
        self.rotationEchelle.minRot = {};
        self.rotationEchelle.minRot[1] = Utils.degToRad(Utils.getNoNil(x, 0));
        self.rotationEchelle.minRot[2] = Utils.degToRad(Utils.getNoNil(y, 0));
        self.rotationEchelle.minRot[3] = Utils.degToRad(Utils.getNoNil(z, 0));

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

        self.rotationEchelle.rotTime = Utils.getNoNil(getXMLString(xmlFile, "vehicle.rotationEchelle#rotTime"), 2)*1000;
        self.rotationEchelle.touchRotLimit = Utils.degToRad(Utils.getNoNil(getXMLString(xmlFile, "vehicle.rotationEchelle#touchRotLimit"), 10));
    end; 	

	-- Sounds --
	
    BuseSoundFile = Utils.getFilename("Sounds/BuseSound.ogg", self.baseDirectory);
    self.BuseSoundId = createSample("BuseSound");
    loadSample(self.BuseSoundId, BuseSoundFile, false);
    self.BusePlaying = false;
   
    BatteurSoundFile = Utils.getFilename("Sounds/Treshing.ogg", self.baseDirectory);
    self.BatteurSoundId = createSample("BatteurSound");
    loadSample(self.BatteurSoundId, BatteurSoundFile, false);
    self.BatteurPlaying = false;
	
    BatteurStartSoundFile = Utils.getFilename("Sounds/startTreshing2.ogg", self.baseDirectory);
    self.BatteurStartSoundId = createSample("BatteurStartSound");
    loadSample(self.BatteurStartSoundId, BatteurStartSoundFile, false);
    self.BatteurStartPlaying = false;

    BatteurStopSoundFile = Utils.getFilename("Sounds/treshingStop2.ogg", self.baseDirectory);
    self.BatteurStopSoundId = createSample("BatteurStopSound");
    loadSample(self.BatteurStopSoundId, BatteurStopSoundFile, false);
    self.BatteurStopPlaying = false;
	

	
	
	-- selfs --
    self.Rouleau = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.Rouleau#index"));
    self.Helice1 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.Helice1#index"));
    self.Helice2 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.Helice2#index"));
    self.Rotor = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.Rotor#index"));
    self.visTremie = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.visTremie#index"));
    self.BuseDot = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.BuseDot#index"));
    self.TankDot1 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.TankDot1#index"));
    self.TankDot2 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.TankDot2#index"));
    self.TankDot3 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.TankDot3#index"));
    self.FuelDot = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.FuelDot#index"));
    self.retroG = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.retroG#index"));
    self.retroD = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.retroD#index"));
    self.backward_lights = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.backward_lights#index"));
    self.WorkLights = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.WorkLights#index"));
    self.ThreshingActive = false;
	self.ThreshingSound = false;
	self.WorkLightsActive = false;
	self.Echelle = true;	
    self.setGrainTankFillLevel = SpecializationUtil.callSpecializationsFunction("setGrainTankFillLevel");
	self.HUDActive = true;
	self.RetroActive = false;
	self.BatteurOK = false;
	self.TreshedNumber = 0;
	self.TreshedTotalNumber = 0;
	self.strawToggleTime = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.strawParticleSystems#toggleTime"), 3500);
	
	-- HUD --
	
	self.HUDpath = Utils.getFilename("HUD_Controls.png", self.baseDirectory);
	self.HUDWidth = 0.100;
    self.HUDHeight = 0.700;
	self.HUDPoxX = 0.9;
    self.HUDPoxY = 0.18
    self.HUDOverlay = Overlay:new("HUD", self.HUDpath, self.HUDPoxX, self.HUDPoxY, self.HUDWidth, self.HUDHeight);

end;

function JDT660i:loadFromAttributesAndNodes(xmlFile, key, resetVehicles)
   local TreshedTotalNumber =  Utils.getNoNil(getXMLFloat(xmlFile, key.."#TreshedTotalNumber"),0);
   self.TreshedTotalNumber = TreshedTotalNumber;
    return BaseMission.VEHICLE_LOAD_OK;
end;

function JDT660i:getSaveAttributesAndNodes(nodeIdent)
   local TreshedTotalNumber= Utils.getNoNil(self.TreshedTotalNumber, 10);
    local attributes = 'TreshedTotalNumber="'..string.format("%.1f",TreshedTotalNumber)..'"';
   return attributes, nil;
end;



function JDT660i:delete()
    delete(self.BuseSoundId);
    delete(self.BatteurStartSoundId);
    delete(self.BatteurStopSoundId);
    delete(self.BatteurSoundId);
end;

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

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

      if isDown and sym == self.keys.Tremie then
            self.Go.Batteur = not self.Go.Batteur;
            self.Done.Batteur = true;
      end;
		
		if isDown and sym == self.keys.Batteur and self.isMotorStarted then
			self.ThreshingActive = not self.ThreshingActive;
			self.ThreshingSound = not self.ThreshingSound;
			self.BatteurOK = not self.BatteurOK;
			local BatteurSoundOffset = 4050;
			self.playBatteurSoundTime = self.time+BatteurSoundOffset;
		end	

		if isDown and sym == self.keys.Echelle then
			self.Echelle = not self.Echelle;
		end;

		if isDown and sym == self.keys.WorkLights then
			self.WorkLightsActive = not self.WorkLightsActive;
		end;
		
		if isDown and sym == self.keys.HUD then
			self.HUDActive = not self.HUDActive;
		end;
		
		if isDown and sym == self.keys.retro then
			self.RetroActive = not self.RetroActive;
		end;
end;

function JDT660i:update(dt)
    	
		-- Movements --

		local doRotate = self.rotationColonneMax or self.rotationColonneMin 
	if self.rotationColonne ~= nil and doRotate then
        local x, y, z = getRotation(self.rotationColonne.node);
        local rot = {x,y,z};
        local newRot = Utils.getMovedLimitedValues(rot, self.rotationColonne.maxRot, self.rotationColonne.minRot, 3, self.rotationColonne.rotTime, dt, not self.rotationColonneMax);
        setRotation(self.rotationColonne.node, unpack(newRot));
    end;	
	
	local doRotate = self.rotationEchelleMax or self.rotationEchelleMin 
	if self.rotationEchelle ~= nil and doRotate then
        local x, y, z = getRotation(self.rotationEchelle.node);
        local rot = {x,y,z};
        local newRot = Utils.getMovedLimitedValues(rot, self.rotationEchelle.maxRot, self.rotationEchelle.minRot, 3, self.rotationEchelle.rotTime, dt, not self.rotationEchelleMax);
        setRotation(self.rotationEchelle.node, unpack(newRot));
    end;
	
		-- Echelle --
		
	if self.Echelle then
		self.rotationEchelleMax = true;
		self.rotationEchelleMin = false;
	else
		self.rotationEchelleMax = false;
		self.rotationEchelleMin = true;
	end;
	-- Threshing Movements --
		
	if self.ThreshingActive then 
	
		rotate(self.Rouleau, dt*0.005, 0, 0);
		rotate(self.Helice2, dt*0, 0, 100);
		rotate(self.Helice1, dt*0, 0, 100);
		rotate(self.visTremie, dt*0, 15, 0);
		rotate(self.Rotor, dt*0.005, 0, 0);

	end;
	
	-- Threshing Sounds --

	
	if self.ThreshingSound and self:getIsActiveForSound() then
        if not self.BatteurStartPlaying then
			playSample(self.BatteurStartSoundId, 1, 1, 0);
			self.BatteurStartPlaying = true;
			stopSample(self.BatteurStopSoundId);
			self.BatteurStopPlaying = false;
		end;
	else
        if self.BatteurStartPlaying then
			stopSample(self.BatteurStartSoundId);
			self.BatteurStartPlaying = false;
			playSample(self.BatteurStopSoundId, 1, 1, 0);
			self.BatteurStopPlaying = true;	
		end;
	end;
	
	if self.ThreshingSound and self:getIsActiveForSound() then
		if self.playBatteurSoundTime <= self.time then
			if not self.BatteurPlaying then
				playSample(self.BatteurSoundId, 0, 1, 0);
				self.BatteurPlaying = true;
			end;
		end;
	else
			if self.BatteurPlaying then
				stopSample(self.BatteurSoundId);
				self.BatteurPlaying = false;
			end;
	end;
	
	if not self.isMotorStarted then
		self.ThreshingActive = false;
		self.ThreshingSound = false;
		self.BatteurOK = false;
	    self.BatteurStartPlaying = false;
	    self.BatteurStopPlaying = false;
	    self.BatteurPlaying = false;
		if self.BatteurPlaying ~= nil then
			stopSample(self.BatteurSoundId);
		end;
		if self.threshingSound ~= nil then
			stopSample(self.threshingSound);
		end;
	end	

	if not self.isEntered then
	    self.BatteurStartPlaying = false;
	    self.BatteurStopPlaying = false;
	    self.BatteurPlaying = false;
	end;
	
	-- Threshing conditions --
	
	if self.BatteurOK and self.isMotorStarted then
		self.allowsThreshing = true;
	else
		self.allowsThreshing = false;	
	end;
	
	-- Animations --	
		
	if self.Go.Batteur ~= nil and self.Done.Batteur then
		self:anim("Batteur", false); 
	end; 
	
	if self.grainTankFillLevel > 0 and not self.Go.Batteur then
		self.Go.Batteur = true;
		self.Done.Batteur = true;
	end;
	
	-- Ha Treshed --
		--self.TreshedNumber = g_currentMission.missionStats.hectaresThreshedSession
		
		if self.isThreshing then
		local pixelToQm = 2048 / 4096 * 2048 / 4096; -- 4096px are mapped to 2048m
		self.TreshedNumber = self.TreshedNumber + self.lastArea*pixelToQm/(40000);
		self.TreshedTotalNumber = self.TreshedTotalNumber + self.lastArea*pixelToQm/(40000);
		end;
	
			--self.TESTNUMBER = g_currentMission.missionStats.hectaresThreshedSession;
	-- Hide/Show Parts --
	
	if self.reverseDriveSoundEnabled then
		setVisibility(self.backward_lights, true);
	else
		setVisibility(self.backward_lights, false);
    end;
	
	local percent = self.grainTankFillLevel/self.grainTankCapacity*100;
	if percent > 75 then
		setVisibility(self.TankDot1, true);
    else
		setVisibility(self.TankDot1, false);
    end;
	if percent > 95 then
		setVisibility(self.TankDot2, true);
    else
		setVisibility(self.TankDot2, false);
    end;
	if percent == 100 then
		setVisibility(self.TankDot3, true);
    else
		setVisibility(self.TankDot3, false);
    end;
	
	local fuelWarn = 100;
	if self.fuelFillLevel < fuelWarn then
		setVisibility(self.FuelDot, true);
    else
		setVisibility(self.FuelDot, false);
    end;
	
	if	self.WorkLightsActive then
		setVisibility(self.WorkLights, true);
	else
		setVisibility(self.WorkLights, false);
	end;

	if self.Echelle then
		setVisibility(self.CAPanel, true);
	else
		setVisibility(self.CAPanel, false);
	end;
	
	if self.RetroActive then
		setVisibility(self.retroG, true);
		setVisibility(self.retroD, true);
	else
		setVisibility(self.retroG, false);
		setVisibility(self.retroD, false);
	end;	

	-- Pipe System + sound --
	if self.isMotorStarted then
	
	if self.pipeParticleActivated then
		setVisibility(self.BuseDot, true);
	else
		setVisibility(self.BuseDot, false);
	end;
	
	if self.pipeParticleActivated  and self:getIsActiveForSound() then
        if not self.BusePlaying then
            playSample(self.BuseSoundId, 0, 1, 0);
            self.BusePlaying = true;
        end;
    else
        if self.BusePlaying then
            stopSample(self.BuseSoundId);
            self.BusePlaying = false;
        end;
    end;
	
	end;
			
end;

function JDT660i:onLeave()
		self.rotationColonneMin = true;
		self.rotationColonneMax = false;
end;

function JDT660i:onEnter()
		self.rotationColonneMin = true;
		self.rotationColonneMax = false;
end;

function JDT660i:draw()
	if self.isEntered then
		g_currentMission:addExtraPrintText(string.format("Touche 0: HUD ON/OFF"));
		if self.HUDOverlay ~= nil then
			if self.HUDActive then
				self.HUDOverlay:render();
				setTextBold(true);
				setTextColor(0, 0, 0, 1.0);
				renderText(0.96, 0.22, 0.016, string.format("%.1f", self.TreshedNumber));
				renderText(0.96, 0.205, 0.016, string.format("%.1f", self.TreshedTotalNumber));
				--renderText(0.5, 0.9350, 0.040, string.format(self.RandomNumber));

			end;
		end;
	end;
	
end;

function JDT660i:anim(varName, loopCheck)
	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 JDT660i:onDeactivateSounds()
    if self.BatteurPlaying ~= nil then
		stopSample(self.BatteurSoundId);
    end;
end;

