--
-- usage
-- Specialization for usage
--
-- @author:		Michi77
-- @date:		24/12/15
-- @version:	v1.0
-- @history:	v1.0 - initial version
--
-- free for non-commercial usage
-- @note uses some code by fruktor (Claas Quadrant 1200)

usage = {};

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

function usage:load(xmlFile)
	self.currentSpeed = 0;
	self.isusage = false;
	self.timerI = 0;
	self.calcShownActLoad = SpecializationUtil.callSpecializationsFunction("calcShownActLoad");	
	self.setShownActLoad = SpecializationUtil.callSpecializationsFunction("setShownActLoad");	
	self.setIsBlocked = SpecializationUtil.callSpecializationsFunction("setIsBlocked");
	self.isBlocked = false;
	self.blockTimer = 0;
	self.blockMaxTime = 1500;	
	local nodeIndex = getXMLString(xmlFile, "vehicle.usageBaseNode#index");
	local usageBaseNode;
	if nodeIndex==nil then
		usageBaseNode = self.components[1].node;
	else
		usageBaseNode = Utils.indexToObject(self.components, nodeIndex);
	end;
	self.maximalWidth = 0;
	self.currentWidth = 0;
	self.pucleanNode = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.lexion600Gui.dirt#cleanNode"));
	
	self.lastFillChangeTime = 0;
	self.currentActLoad = 0;
	self.showActLoad = 0;
	self.lastFillLevelDelta = 0;
	self.currentStep = 1;
	self.time = 0;
	self.maxLoad = 70;
	self.lastDeltaFill = 0;
	self.fillLevel1 = 0;
	self.fillLevel2 = 0;
	self.soundPlayed = false;
	self.soundTimer = 0;
	self.lastActLoad = 0;
	self.fillingDeltas = {};
	self.lastAreaForCalc = 0;
	self.hud2 = {};
	local width = 0.1734375;
	local height = 0.025000000372529;
	local w = 0;
	local h = 0.0025;
	self.hud2.xPos = 1-width;
	self.hud2.yPos = h;
	self.hud2.hudWidth = width;	
	self.hud2.overlay_hud 	= Overlay:new("loadHUD_hud", 	Utils.getFilename("hud/hud_block.dds", self.baseDirectory), self.hud2.xPos, self.hud2.yPos, width, height);
	self.hud2.overlay_bar 	= Overlay:new("loadHUD_bar", 	Utils.getFilename("hud/hud_barY.dds", self.baseDirectory), self.hud2.xPos, self.hud2.yPos, width, height);	
end;

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

function usage:keyEvent(unicode, sym, modifier, isDown)
end;

function usage:update(dt)
	if self.isBlocked and self.isTurnedOn then
		self:setIsTurnedOn(false);
	end;
	if g_currentMission.player ~= nil then
		local pvx, pvy, pvz = getWorldTranslation(g_currentMission.player.rootNode);
		local px, py, pz = getWorldTranslation(self.pucleanNode);
		local distance = Utils.vector3Length(px-pvx, py-pvy, pz-pvz);
		if distance < 2 then
			if self.isBlocked then
				g_currentMission:addHelpButtonText( g_i18n:getText("COMBINE_CLEAN"), InputBinding.IMPLEMENT_EXTRA);
				if InputBinding.hasEvent(InputBinding.IMPLEMENT_EXTRA) then
					self:setIsBlocked(false);
				end;
			end;
		end;
	end;
end;
 
function usage:readUpdateStream(streamId, timestamp, connection) 
    if connection:getIsServer() then 
        self.lastAreaForCalc = streamReadFloat32(streamId); 
    end; 
end; 
 
function usage:writeUpdateStream(streamId, connection, dirtyMask) 
    if not connection:getIsServer() then 
        streamWriteFloat32(streamId, self.lastAreaForCalc); 
    end;  
end; 

function usage:updateTick(dt)
	if not self.isAIThreshing and not (self.cp ~= nil and self.cp.isDriving ) then
		if self.combineIsFilling then

			if self.isServer then 
				self.lastAreaForCalc = self.lastArea;
			end;
			
			if FruitUtil.fruitIndexToDesc[self.lastValidFillType] ~= nil and FruitUtil.fruitIndexToDesc[self.lastValidFillType].literPerSqm ~= nil then
				self.fillingDeltas[self.timerI] = ((self.lastAreaForCalc * g_currentMission:getFruitPixelsToSqm())*FruitUtil.fruitIndexToDesc[self.lastValidFillType].literPerSqm*self.threshingScale) * 2.6;		
			else
				self.fillingDeltas[self.timerI] = ((self.lastAreaForCalc * g_currentMission:getFruitPixelsToSqm())*FruitUtil.fruitIndexToDesc[1].literPerSqm*self.threshingScale) * 2.6;		
			end;
			if self.timerI == 10 then
				self.time = 0;
				self.timerI = 0;
				self.lastFillChangeTime = self.time;
				deltaFill = (self.fillLevel1 + self.fillLevel2) / 10;
				for k in pairs (self.fillingDeltas) do
					deltaFill = deltaFill + self.fillingDeltas[k];
				end;
				for k in pairs (self.fillingDeltas) do
					self.fillingDeltas[k] = nil;
				end;
				if self.lastActLoad == deltaFill then
					self.currentActLoad = deltaFill + 1;
				else
					self.currentActLoad = deltaFill;
				end;
				self.lastActLoad = self.currentActLoad;
			end;
		else
			self.time = self.time + dt;
			self.lastFillChangeTime = self.time;
		end;
		if not self.combineIsFilling  then
			self.time = self.time + dt;
			self.lastFillChangeTime = self.time;
		end;
		if (self.lastFillChangeTime > 1000 and self.currentActLoad > 0) then
			self.currentActLoad = 0;
		end;
		self:calcShownActLoad(self.currentActLoad);
		
		self.currentSpeed = self:getLastSpeed() * self.speedDisplayScale;
		local percentage = math.min(self.currentWidth/self.maxLoad, 1);
		if percentage > 0.85 and not self.soundPlayed then
			self:playCebisSound();
			self.soundPlayed = true;
		end;
		
		if self.currentWidth == self.maxLoad and self.currentSpeed > 6 then 
			self.blockTimer = self.blockTimer + dt;
			if self.blockTimer > self.blockMaxTime then
				if not self.isBlocked then
					self.blockTimer = 0;
					self:setIsBlocked(true);
					if not self.soundPlayed then
						self:playCebisSound();
						self.soundPlayed = true;
					end;
				end
			end;
		else
			self.blockTimer = math.max(0, self.blockTimer - dt);
		end;
		if self.soundPlayed then
			self.soundTimer = self.soundTimer + 1;
		end;
		self.timerI = self.timerI + 1;
		if self.timerI > 10 then
			self.timerI = 0;
		end;
		if self.soundTimer >= 100 then
			self.soundPlayed = false;
			self.soundTimer = 0;
		end;
	else
		self.currentWidth = 0;
	end;
end;

function usage:draw()
	setTextColor(1.0, 1.0, 1.0, 1.0);

	setTextBold(false);			
	setTextAlignment(RenderText.ALIGN_LEFT);

	local percentage = math.min(self.currentWidth/self.maxLoad, 1);
	
	if percentage > 0.95 then 
		setOverlayColor(self.hud2.overlay_bar.overlayId, 1, 0, 0, 1)
	elseif percentage > 0.85 then
		setOverlayColor(self.hud2.overlay_bar.overlayId, 1, 0.5, 0, 1)	
	else
		setOverlayColor(self.hud2.overlay_bar.overlayId, 0.7, 1, 0, 1)
	end;
	
	self.hud2.overlay_bar.width = self.hud2.hudWidth * percentage;	
	setOverlayUVs(self.hud2.overlay_bar.overlayId, 0, 0.05, 0, 1, percentage, 0.05, percentage, 1);
	self.hud2.overlay_bar:render();	
	
	self.hud2.overlay_hud:render();	
	
	setTextAlignment(RenderText.ALIGN_CENTER);
	local x = 0.043359375;
	local y = 0.0087500001303852;
	
	renderText(self.hud2.xPos+x, self.hud2.yPos+y, 0.012, g_i18n:getText("ACT_LOAD").." "..string.format("%5.2f %%", 100*percentage));
	setTextAlignment(RenderText.ALIGN_LEFT);

	if self.isBlocked then
		g_currentMission:showBlinkingWarning(g_i18n:getText("COMBINE_IS_BLOCKED"), 2000);
	end;
end;

function usage:delete()
end;

function usage:setShownActLoad(act, noEventSend)	
	self.currentWidth = math.max(math.min(act, self.maxLoad), 0);
end;

function usage:calcShownActLoad(target)
	if target == self.currentWidth then
		return;
	end;
	
	local step = self.currentStep * math.abs(self.currentWidth-target)/6;
	
	if self.lastFillChangeTime > 1000 then
		step = step * 10;
	end;
	
	if target > self.currentWidth then
		self:setShownActLoad(math.min(self.currentWidth + step, target));
	else
		self:setShownActLoad(math.max(self.currentWidth - step, target));
	end;
end;

function usage:setIsBlocked(state, noEventSend)
	SetBlockedEvent.sendEvent(self, state, noEventSend);
	self.isBlocked = state;
end;
