--
-- CIH5130
-- Implementation of combine functions and leavers
-- 
-- @author Knagsted
-- @date  16/07/10
-- @date  25/11/14 conversion LS15 by @lex (FraBel LS-Modding) with permission of Knagsted
--
-- Thank you to Bayn for allowing me to reuse parts from the JD 660 script in this implementation
--
-- Do not edit without my permission
--

CIH5130 = {};

function CIH5130.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Combine, specializations);
end;

function CIH5130:load(xmlFile)

	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;

    local rotationPartNodeTanknadel = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.rotationPartTanknadel#index"));
    if rotationPartNodeTanknadel ~= nil then
        self.rotationPartTanknadel = {};
        self.rotationPartTanknadel.node = rotationPartNodeTanknadel;

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

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

        self.rotationPartTanknadel.rotTime = Utils.getNoNil(getXMLString(xmlFile, "vehicle.rotationPartTanknadel#rotTime"), 2)*1000;
        self.rotationPartTanknadel.touchRotLimit = Utils.degToRad(Utils.getNoNil(getXMLString(xmlFile, "vehicle.rotationPartTanknadel#touchRotLimit"), 10));
    end;
	
	local rotationPartNodeVoltnadel = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.rotationPartVoltnadel#index"));
    if rotationPartNodeVoltnadel ~= nil then
        self.rotationPartVoltnadel = {};
        self.rotationPartVoltnadel.node = rotationPartNodeVoltnadel;

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

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

        self.rotationPartVoltnadel.rotTime = Utils.getNoNil(getXMLString(xmlFile, "vehicle.rotationPartVoltnadel#rotTime"), 2)*1000;
        self.rotationPartVoltnadel.touchRotLimit = Utils.degToRad(Utils.getNoNil(getXMLString(xmlFile, "vehicle.rotationPartVoltnadel#touchRotLimit"), 10));
    end;
	
	local rotationPartNodeTempnadel = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.rotationPartTempnadel#index"));
    if rotationPartNodeTempnadel ~= nil then
        self.rotationPartTempnadel = {};
        self.rotationPartTempnadel.node = rotationPartNodeTempnadel;

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

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

        self.rotationPartTempnadel.rotTime = Utils.getNoNil(getXMLString(xmlFile, "vehicle.rotationPartTempnadel#rotTime"), 2)*1000;
        self.rotationPartTempnadel.touchRotLimit = Utils.degToRad(Utils.getNoNil(getXMLString(xmlFile, "vehicle.rotationPartTempnadel#touchRotLimit"), 10));
		
		self.Rotor = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.Rotor#index"));
		
		BatteurSoundFile = Utils.getFilename("Sounds/caseIH5130_work.wav", self.baseDirectory);
		self.BatteurSoundId = createSample("BatteurSound");
		loadSample(self.BatteurSoundId, BatteurSoundFile, false);
		self.BatteurPlaying = false;
	
		BatteurStartSoundFile = Utils.getFilename("Sounds/caseIH5130_startwork.wav", self.baseDirectory);
		self.BatteurStartSoundId = createSample("BatteurStartSound");
		loadSample(self.BatteurStartSoundId, BatteurStartSoundFile, false);
		self.BatteurStartPlaying = false;

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

		self.fan = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.fan#index"));
		self.fanRotation = 0;
		self.engineRunTime = 0;		
	
	-- Init of self values
	
	self.HUDActive = true;	
	self.BatteurOK = false;	
	
	-- HUD --	
	self.HUDpath = Utils.getFilename("model_textures/HUD_Controls.png", self.baseDirectory);
	self.HUDWidth = 0.100;
    self.HUDHeight = 0.04;
	self.HUDPoxX = 0.90;
    self.HUDPoxY = 0.872;
    self.HUDOverlay = Overlay:new("HUD", self.HUDpath, self.HUDPoxX, self.HUDPoxY, self.HUDWidth, self.HUDHeight);

	self.rotorSpeedValue = 350;
	self.actualRotorSpeedValue = 0;
	self.rotorSpeedAdjustMode = 0;
	self.lastThreasherRoundPerMinute = 0;
	self.threasherActivationTime = 2500;
	self.reelTime = 0;
	self.threshingTime = 0;
end;

function CIH5130:delete()
	stopSample(self.BatteurStartSoundId);
    stopSample(self.BatteurStopSoundId);
    stopSample(self.BatteurSoundId);
end;

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

function CIH5130:keyEvent(unicode, sym, modifier, isDown)		
		
		if isDown and sym == self.keys.HUD then
			self.HUDActive = not self.HUDActive;
		end;		
		
		if isDown and sym == Input.KEY_KP_7 then
			self.rotorSpeedAdjustMode = 1;
		else 
			self.rotorSpeedAdjustMode = 0;
		end;
		
		if isDown and sym == Input.KEY_KP_9 then
			self.rotorSpeedAdjustMode = -1;
		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
end;

function CIH5130:update(dt)	
	
	if self.isMotorStarted then
		if self.rotationPartTanknadel ~= nil then
			local x, y, z = getRotation(self.rotationPartTanknadel.node);
			z = ((self.rotationPartTanknadel.maxRot[3] - self.rotationPartTanknadel.minRot[3]) / self.fuelCapacity) * self.fuelFillLevel + self.rotationPartTanknadel.minRot[3];
			setRotation(self.rotationPartTanknadel.node, x, y ,z);
		end;
		
		if self.rotationPartVoltnadel ~= nil then
			setRotation(self.rotationPartVoltnadel.node, 0, 0,Utils.degToRad(55));
		end;
		
		if self.rotationPartTempnadel ~= nil then
			setRotation(self.rotationPartTempnadel.node, 0, 0,Utils.degToRad(45));
		end;
	else
		setRotation(self.rotationPartTanknadel.node, 0, 0 ,Utils.degToRad(-15));
		setRotation(self.rotationPartVoltnadel.node, 0, 0 ,Utils.degToRad(-15));
		setRotation(self.rotationPartTempnadel.node, 0, 0 ,Utils.degToRad(-15));
	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.BatteurSoundId ~= nil then
		local alpha = 0.9;
		local roundPerMinute = self.lastThreasherRoundPerMinute*alpha + (1-alpha)*(self.actualRotorSpeedValue);
		self.lastThreasherRoundPerMinute = roundPerMinute;
		local roundPerSecond = roundPerMinute / 60;
		setSamplePitch(self.BatteurSoundId, math.min(1 + 0.01*math.abs(roundPerSecond), 3));
	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 self.rotorSpeedAdjustMode == 1 then
		if self.rotorSpeedValue < 550 then
			self.rotorSpeedValue = self.rotorSpeedValue + 0.01 * dt;
		end;
	elseif self.rotorSpeedAdjustMode == -1 then
		if self.rotorSpeedValue > 150 then
			self.rotorSpeedValue = self.rotorSpeedValue - 0.01 * dt;
		end;
	end;
	
	if self.key ~= nil then
		if self.isMotorStarted and self.engineRunTime < 1500 then
			setRotation(self.key, 0,Utils.degToRad(-90) ,Utils.degToRad(-24));
		elseif self.isMotorStarted then
			setRotation(self.key, 0,Utils.degToRad(-50) ,Utils.degToRad(-24));
		else
			setRotation(self.key, 0,Utils.degToRad(0) ,Utils.degToRad(-24));
		end;
	end;
	
	-- Threashing off --
	if not self.isMotorStarted then		
		self.ThreshingActive = false;
		self.ThreshingSound = false;
		self.BatteurOK = false;
		
		if self.threshingSound ~= nil then
			stopSample(self.threshingSound);
		end;		
	end;

	-- Threshing conditions --
	
	if self.isMotorStarted and not self.BatteurOK then
		self.allowsThreshing = false;
	else
		self.allowsThreshing = true;	
	end;
	
	--local rpm = self.rpmNum;
	local rpm = 3;
	local engineRpm = 3;
	
	if rpm > 3 then
		rpm = 3;
	end;
	
	engineRpm = rpm;

	if self.isMotorStarted then
		rotate(self.fan, dt * 0.004 * rpm, 0, 0);
		self.engineRunTime = dt + self.engineRunTime;
	else
		self.engineRunTime = 0;
	end;
	
	self.actualRotorSpeedValue = self.rotorSpeedValue * rpm;
	local reelRpm = rpm/self.threasherActivationTime * self.reelTime;
	
	rpm = rpm/self.threasherActivationTime * self.threshingTime;
	self.actualRotorSpeedValue = self.actualRotorSpeedValue/self.threasherActivationTime * self.threshingTime;
	
	if self.reelTime < self.threasherActivationTime and self.isCutterStarted then
		self.reelTime = self.reelTime + dt;
		if self.reelTime > self.threasherActivationTime then
			self.reelTime = self.threasherActivationTime;
		end;
	end;

	if self.reelTime > 0 and not self.isCutterStarted then
		self.reelTime = self.reelTime - dt/2;
		if self.reelTime < 0 then
			self.reelTime = 0;
		end;
	end;
	
	if self.threshingTime < self.threasherActivationTime and self.ThreshingActive then
		self.threshingTime = self.threshingTime + dt;
		if self.threshingTime > self.threasherActivationTime then
			self.threshingTime = self.threasherActivationTime;
		end;
	end;

	if self.threshingTime > 0 and not self.ThreshingActive then
		self.threshingTime = self.threshingTime - dt/2;
		if self.threshingTime < 0 then
			self.threshingTime = 0;
		end;
	end;
end;

function CIH5130:draw()
if self.isEntered then
		g_currentMission:addHelpButtonText(g_i18n:getText("INCREASE_THREASHER_CIH5130"), InputBinding.INCREASE_THREASHER_CIH5130);
		g_currentMission:addHelpButtonText(g_i18n:getText("DECREASE_THREASHER_CIH5130"), InputBinding.DECREASE_THREASHER_CIH5130);
		g_currentMission:addHelpButtonText(g_i18n:getText("SELECTGRAINTYPE_CIH5130"), InputBinding.SELECTGRAINTYPE_CIH5130);
		g_currentMission:addHelpButtonText(g_i18n:getText("HUD_CIH5130"), InputBinding.HUD_CIH5130);
		g_currentMission:addHelpButtonText(g_i18n:getText("BAR_CIH5130"), InputBinding.BAR_CIH5130);
		g_currentMission:addHelpButtonText(g_i18n:getText("DISPLAY_CIH5130"), InputBinding.DISPLAY_CIH5130);
		g_currentMission:addHelpButtonText(g_i18n:getText("convoi_CIH5130"), InputBinding.convoi_CIH5130);
		if self.HUDOverlay ~= nil then
			if self.HUDActive then
				self.HUDOverlay:render();				
			end;
		end;
	end;
end;

function CIH5130:onDeactivateSounds()
    if self.BatteurPlaying ~= nil then
		stopSample(self.BatteurSoundId);
    end;
end;