--
-- ThreshingCounter
-- Specialization for counting threshed hectars
--
-- @author:  	Manuel Leithner
-- @date:		15/11/11
-- @version:	v1.0
-- @history:	v1.0 - initial implementation
--

ThreshingCounter = {};

function ThreshingCounter.prerequisitesPresent(specializations)
    return true;
end;

function ThreshingCounter:load(xmlFile)

	self.sessionHectars = 0;	
	self.totalHectars = 0;
	self.tcX = Utils.getNoNil(getXMLFloat(xmlFile,  "vehicle.ThreshingCounter#posX"), 0.7543);
	self.tcY = Utils.getNoNil(getXMLFloat(xmlFile,  "vehicle.ThreshingCounter#posY"), 0.213);
	self.yOffset = 0.0085;
	
	self.tcOverlay = Overlay:new("hudTCOverlay", Utils.getFilename("textur/ThreshingCounter_hud.dds", self.baseDirectory), self.tcX, self.tcY, 0.2371, 0.039525);	
	
	self.lastAreaSent = 0;
	
	self.lastActiveFruitType = FruitUtil.FRUITTYPE_UNKNOWN;
end;

function ThreshingCounter:delete()
end;

function ThreshingCounter:readStream(streamId, connection)
	local session = streamReadFloat32(streamId);
	local total = streamReadFloat32(streamId);	
	self.sessionHectars = session;
	self.totalHectars = total;
end;

function ThreshingCounter:writeStream(streamId, connection)	
	streamWriteFloat32(streamId, self.sessionHectars);
	streamWriteFloat32(streamId, self.totalHectars);
	self.lastAreaSent = 0;
end;

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

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

function ThreshingCounter:update(dt)
end;

function ThreshingCounter:updateTick(dt)
	if self.isServer and self.isThreshing then	
		local lastArea = 0;
		for cutter,implement in pairs(self.attachedCutters) do
			lastArea = lastArea + Utils.getNoNil(cutter.lastRealArea, 0);
		end;
		
		local pixelToSqm = g_currentMission:getFruitPixelsToSqm();
		local sqm = lastArea*pixelToSqm;
		local ha = sqm/10000;		
		self.lastAreaSent = self.lastAreaSent + ha;	
	
		self.sessionHectars = self.sessionHectars + ha;
		self.totalHectars = self.totalHectars + ha;	
		
		if self.lastAreaSent > 0.02 then
			g_server:broadcastEvent(ThreshingCounterEvent:new(self, self.lastAreaSent));
			self.lastAreaSent = 0;
		end;
	end;
end;

function ThreshingCounter:draw()
	
	local counterSession = math.floor(self.sessionHectars*100) / 100;
	local counterTotal = math.floor(self.totalHectars*10) / 10;
	local fullSession = math.floor(counterSession);
	local fullTotal = math.floor(counterTotal);
	local deciSession = math.floor((counterSession - fullSession)*100);
	if deciSession < 10 then
		deciSession = "0" .. deciSession;
	end;
	local deciTotal = math.floor((counterTotal - fullTotal)*10);
	
	self.tcOverlay:render();
	setTextAlignment(RenderText.ALIGN_RIGHT);
	setTextBold(true);	
	setTextColor(0, 0, 0, 1);
    renderText(self.tcX+0.068, self.tcY+self.yOffset - 0.003, 0.022, tostring(fullTotal) .. ",");
	renderText(self.tcX+0.059+0.2371/2, self.tcY+self.yOffset - 0.003, 0.022, tostring(fullSession) .. ",");
	setTextColor(1,1,1,1);
	renderText(self.tcX+0.068, self.tcY+self.yOffset, 0.022, tostring(fullTotal) .. ",");
	renderText(self.tcX+0.059+0.2371/2, self.tcY+self.yOffset, 0.022, tostring(fullSession) .. ",");
	setTextColor(0, 0, 0, 1);
    renderText(self.tcX+0.077, self.tcY+self.yOffset - 0.003, 0.023, tostring(deciTotal));
	renderText(self.tcX+0.077 + 0.2371/2, self.tcY+self.yOffset - 0.003, 0.023, tostring(deciSession));
	setTextColor(0.95,0,0,1);
	renderText(self.tcX+0.077, self.tcY+self.yOffset, 0.023, tostring(deciTotal));
	renderText(self.tcX+0.077 + 0.2371/2, self.tcY+self.yOffset, 0.023, tostring(deciSession));
	setTextColor(0, 0, 0, 1);
    renderText(self.tcX+0.097, self.tcY+self.yOffset - 0.003, 0.023, "ha");
	renderText(self.tcX+0.097+0.2371/2, self.tcY+self.yOffset - 0.003, 0.023, "ha");
	setTextColor(1,1,1,1);
	renderText(self.tcX+0.097, self.tcY+self.yOffset, 0.023, "ha");
	renderText(self.tcX+0.097+0.2371/2, self.tcY+self.yOffset, 0.023, "ha");
	setTextAlignment(RenderText.ALIGN_LEFT);
end;

function ThreshingCounter:loadFromAttributesAndNodes(xmlFile, key, resetVehicles)	
	if not resetVehicles then
		local totalHectars = Utils.getNoNil(getXMLFloat(xmlFile, key .. "#totalHectars"), self.totalHectars);
		self.totalHectars = totalHectars;
	end; 
    return BaseMission.VEHICLE_LOAD_OK;
end;

function ThreshingCounter:getSaveAttributesAndNodes(nodeIdent)
	local attributes = 'totalHectars="' .. tostring(self.totalHectars) ..'"';
	return attributes, nil;
end;

local oldCutterLoad = Cutter.load;
Cutter.load = function(self, xmlFile)
	oldCutterLoad(self, xmlFile);
	self.lastActiveFruitType = FruitUtil.FRUITTYPE_UNKNOWN;
end;

local oldCutterUpdateTick = Cutter.updateTick;
Cutter.updateTick = function(self, dt)
	if self.isServer then
		self.lastRealArea = 0;
		if self.reelStarted and self.movingDirection < 0 then
			local allowsThreshing = true;
			if self.attacherVehicle ~= nil then
				allowsThreshing = self.attacherVehicle.allowsThreshing;
			end;
			
			if allowsThreshing then
				if self.currentFruitType ~= FruitUtil.FRUITTYPE_UNKNOWN then
					self.lastActiveFruitType = self.currentFruitType;
				end;
				
				local lastArea = 0;
				for _,area in pairs(self.cuttingAreas) do
					if self:getIsAreaActive(area) then
						local x,_,z = getWorldTranslation(area.start);
						local x1,_,z1 = getWorldTranslation(area.width);
						local x2,_,z2 = getWorldTranslation(area.height);	

						local ids = g_currentMission.fruits[self.lastActiveFruitType];
						if ids == nil or ids.id == 0 then
							break;
						end;
						local id = ids.id;						
						local desc = FruitUtil.fruitIndexToDesc[self.lastActiveFruitType];
						setDensityReturnValueShift(id, -1);
						setDensityMaskParams(id, "greater", desc.minHarvestingGrowthState);
						local x,z, widthX,widthZ, heightX,heightZ = Utils.getXZWidthAndHeight(id, x, z, x1, z1, x2, z2);
						local area, total = getDensityParallelogram(id, x, z, widthX, widthZ, heightX, heightZ, 0, 3);						
						setDensityReturnValueShift(id, 0);
						setDensityMaskParams(id, "greater", 0);						
						area = area / g_currentMission.maxFruitValue;						
						lastArea = lastArea + area;
					end;
				end;
				
				self.lastRealArea = lastArea;
			end;
		end;	
	end;
	
	oldCutterUpdateTick(self, dt);
end;


ThreshingCounterEvent = {};
ThreshingCounterEvent_mt = Class(ThreshingCounterEvent, Event);

InitEventClass(ThreshingCounterEvent, "ThreshingCounterEvent");

function ThreshingCounterEvent:emptyNew()
    local self = Event:new(ThreshingCounterEvent_mt);
    self.className="ThreshingCounterEvent";
    return self;
end;

function ThreshingCounterEvent:new(vehicle, lastArea)
    local self = ThreshingCounterEvent:emptyNew()
    self.vehicle = vehicle;
	self.lastArea = lastArea;
    return self;
end;

function ThreshingCounterEvent:readStream(streamId, connection)
	local vehicle = networkGetObject(streamReadInt32(streamId));
	local newHectars = streamReadFloat32(streamId);
	vehicle.sessionHectars = vehicle.sessionHectars + newHectars;
	vehicle.totalHectars = vehicle.totalHectars + newHectars;
end;

function ThreshingCounterEvent:writeStream(streamId, connection)
    streamWriteInt32(streamId, networkGetObjectId(self.vehicle));
	streamWriteFloat32(streamId, self.lastArea);
end;

function ThreshingCounterEvent:run(connection)
end;