--
-- New StrawMod script for small bales
-- @author: Burner
--
--Filllevel Anzeige: HoT
--
source("dataS/scripts/vehicles/specializations/SetTurnedOnEvent.lua");
StrawMod = {};

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

function StrawMod:load(xmlFile)
    self.setIsTurnedOn = SpecializationUtil.callSpecializationsFunction("setIsTurnedOn");
	self.objectInRange = StrawMod.objectInRange;
    self.fillScale = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.fillScale#value"), 1);
    self.wasToFast = false;
    self.isTurnedOn = true;
	self.currentFruitType = FruitUtil.FRUITTYPE_UNKNOWN;
    self.lastStrawModArea = 0;
    self.StrawModGroundFlag = self:getNextDirtyFlag();
	
    local strawBalesIndex = getXMLString(xmlFile, "vehicle.strawBales#index");
    self.strawBalesCount = getXMLInt(xmlFile, "vehicle.strawBales#count");
    self.strawBalesRootNode = Utils.indexToObject(self.components, strawBalesIndex);
	
    local hayBalesIndex = getXMLString(xmlFile, "vehicle.hayBales#index");
    self.hayBalesCount = getXMLInt(xmlFile, "vehicle.hayBales#count");
    self.hayBalesRootNode = Utils.indexToObject(self.components, hayBalesIndex);

	self.baleSearchNode = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.baleSearchNode#index"));
	self.baleFillValue = self.capacity/self.strawBalesCount;
	
	-- HUD
	self.file = Utils.getFilename("Texturi/Contor.png", self.baseDirectory);
	self.HUDx = 0.435;
    self.HUDy = 1-0.330;
    self.HUDWidth = 0.320;
    self.HUDHeight = 0.320;
	self.HUD = false;
	
	self.cX = 0.52;
    self.cY = 0.945;
	self.tX = 0.57;
    self.tY = 0.945;
	self.APCurrentwc0 = 0;
	self.APTotalwc0 = 0;
    
	self.APHUD = Overlay:new("APHUD", self.file, self.HUDx, self.HUDy, self.HUDWidth, self.HUDHeight);
end;

function StrawMod:delete()
end;

function StrawMod:readStream(streamId, connection)
    local turnedOn = streamReadBool(streamId);
    self:setIsTurnedOn(turnedOn, true);
    local fillLevel = streamReadInt32(streamId);
end;

function StrawMod:writeStream(streamId, connection)
    streamWriteBool(streamId, self.isTurnedOn);
    streamWriteInt32(streamId, self.fillLevel);
end;

function StrawMod:readUpdateStream(streamId, timestamp, connection)
end;

function StrawMod:writeUpdateStream(streamId, connection, dirtyMask)
end;

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

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

function StrawMod:update(dt)
    if self:getIsActiveForInput() and self:getIsActive() then
        if InputBinding.hasEvent(InputBinding.COUNTER) then
			self.HUD = not self.HUD;
		end;
    end;
end;

function StrawMod:updateTick(dt)
    self.wasToFast = false;
    self.lastStrawModArea = 0;
    if self:getIsActive() then
		self:setIsTurnedOn(true)
		if self.fillLevel == self.capacity then
			self:setIsTurnedOn(false)
			return
		end
		if self.isTurnedOn and self.capacity > self.fillLevel then
            local toFast = self:doCheckSpeedLimit() and self.attacherVehicle.lastSpeed*3600 > 29;
            if self.isServer then
                if not toFast then
					local bale = self:objectInRange(self.baleSearchNode);
					if bale ~= nil then
						baleId = networkGetObjectId(bale);
						bale = networkGetObject(baleId);
						if getUserAttribute(bale.nodeId, "fillType") == "wheat_windrow" then
							if self.currentFillType == Fillable.FILLTYPE_UNKNOWN or self.currentFillType == Fillable.FILLTYPE_WHEAT_WINDROW then
								fillType = Fillable.FILLTYPE_WHEAT_WINDROW;
							elseif self.currentFillType == Fillable.FILLTYPE_DRYGRASS_WINDROW then
								fillType = Fillable.FILLTYPE_DRYGRASS_WINDROW;
							end;
						end;
						if getUserAttribute(bale.nodeId, "fillType") == "dryGrass_windrow" then
							if self.currentFillType == Fillable.FILLTYPE_UNKNOWN or self.currentFillType == Fillable.FILLTYPE_DRYGRASS_WINDROW then
								fillType = Fillable.FILLTYPE_DRYGRASS_WINDROW;
							elseif self.currentFillType == Fillable.FILLTYPE_WHEAT_WINDROW then
								fillType = Fillable.FILLTYPE_WHEAT_WINDROW;
							end;
						end;
						bale:delete();
						self:setFillLevel(self.fillLevel+self.baleFillValue, fillType)
					end;
                end;
            end;
        end;
    end;
	
	setVisibility(self.hayBalesRootNode, true); 
	setVisibility(self.strawBalesRootNode, true); 
	
	for i=1, self.strawBalesCount do
		local strawBale = getChildAt(self.strawBalesRootNode, i-1);
		setVisibility(strawBale, false);
	end;
	
	for i=1, self.hayBalesCount do
		local hayBale = getChildAt(self.hayBalesRootNode, i-1);
		setVisibility(hayBale, false);
	end;
	
	percentDecimal = self.fillLevel/self.capacity;
	if self.currentFillType == Fillable.FILLTYPE_WHEAT_WINDROW then
		self.strawBalesToShow = math.ceil(self.strawBalesCount*percentDecimal);
		for i=1, self.strawBalesToShow do
			local strawBale = getChildAt(self.strawBalesRootNode, i-1);
			setVisibility(strawBale, true);
		end;
	end;
	if self.currentFillType == Fillable.FILLTYPE_DRYGRASS_WINDROW then
		self.hayBalesToShow = math.ceil(self.hayBalesCount*percentDecimal);
		for i=1, self.hayBalesToShow do
			local hayBale = getChildAt(self.hayBalesRootNode, i-1);
			setVisibility(hayBale, true);
		end;
	end;
end;

function StrawMod:draw()
    if self.HUD then
		g_currentMission:addHelpButtonText(string.format(g_i18n:getText("HUD_OFF"), self.typeDesc), InputBinding.COUNTER);
	else
		g_currentMission:addHelpButtonText(string.format(g_i18n:getText("HUD_ON"), self.typeDesc), InputBinding.COUNTER);
	end;
	if self.HUD then
		self.APHUD:render();
		setTextBold(true);
		setTextColor(0, 0, 0, 1.0);
		renderText(self.cX, self.cY, 0.020, "geladene Ballen: ".. string.format(math.ceil(self.fillLevel / self.baleFillValue)) .. " / " .. string.format(self.strawBalesCount));
		setTextBold(false);
	end;
end;

function StrawMod:onDetach()
    if self.deactivateOnDetach then
        StrawMod.onDeactivate(self);
    end;
end;

function StrawMod:onLeave()
    if self.deactivateOnLeave then
        StrawMod.onDeactivate(self);
    end;
end;

function StrawMod:onDeactivate()
    self:setIsTurnedOn(false)
end;

function StrawMod:setIsTurnedOn(turnedOn, noEventSend)
    SetTurnedOnEvent.sendEvent(self, turnedOn, noEventSend)
    self.isTurnedOn = turnedOn;
end;

function StrawMod:objectInRange(refNode)
    local nearestDistance = 6;
    local nearestBale = nil;
    local px, py, pz = getWorldTranslation(refNode);
	for index, item in pairs(g_currentMission.itemsToSave) do
	    itemNode = item.item.nodeId;
	    if getParent(item.item.nodeId) == getRootNode() then
			if item.item:isa(Bale) then
				local vx, vy, vz = getWorldTranslation(itemNode);
				local distance = Utils.vector3Length(px-vx, py-vy, pz-vz);
				if distance < nearestDistance then
					index = index;
					nearestBale = item.item;
					nearestObject = itemNode;
					nearestDistance = distance;
				end;
			end;
		end;
	end;	
    return nearestBale;
end;