--
-- New StrawMod script for small bales
-- @author: Burner
--

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 = false;
	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;
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() then
        if InputBinding.hasEvent(InputBinding.IMPLEMENT_EXTRA) and (self.currentFillType == Fillable.FILLTYPE_UNKNOWN or self.currentFillType == Fillable.FILLTYPE_STRAWBALE or self.currentFillType == Fillable.FILLTYPE_HAYBALE) then
            self:setIsTurnedOn(not self.isTurnedOn);
        end;
    end;
end;

function StrawMod:updateTick(dt)
    self.wasToFast = false;
    self.lastStrawModArea = 0;
    if self:getIsActive() then
        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, "isStrawbale") then
							if self.currentFillType == Fillable.FILLTYPE_UNKNOWN or self.currentFillType == Fillable.FILLTYPE_STRAWBALE then
								fillType = Fillable.FILLTYPE_STRAWBALE;
							elseif self.currentFillType == Fillable.FILLTYPE_HAYBALE then
								fillType = Fillable.FILLTYPE_HAYBALE;
							end;
						end;
						if getUserAttribute(bale.nodeId, "isHaybale") then
							if self.currentFillType == Fillable.FILLTYPE_UNKNOWN or self.currentFillType == Fillable.FILLTYPE_HAYBALE then
								fillType = Fillable.FILLTYPE_HAYBALE;
							elseif self.currentFillType == Fillable.FILLTYPE_STRAWBALE then
								fillType = Fillable.FILLTYPE_STRAWBALE;
							end;
						end;
						bale:delete();
						self:setFillLevel(self.fillLevel+self.baleFillValue, fillType)
					end;
                end;
            end;
            self.wasToFast = toFast;
        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_STRAWBALE 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_HAYBALE 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.wasToFast then
        g_currentMission:addWarning(g_i18n:getText("Dont_drive_to_fast") .. "\n" .. string.format(g_i18n:getText("Cruise_control_levelN"), "2", InputBinding.getKeyNamesOfDigitalAction(InputBinding.SPEED_LEVEL2)), 0.07+0.022, 0.019+0.029);
    end;
    if self.isTurnedOn then
        g_currentMission:addHelpButtonText(string.format(g_i18n:getText("turn_off_OBJECT"), g_i18n:getText("collectBales")), InputBinding.IMPLEMENT_EXTRA);
    else
        g_currentMission:addHelpButtonText(string.format(g_i18n:getText("turn_on_OBJECT"), g_i18n:getText("collectBales")), InputBinding.IMPLEMENT_EXTRA);
    end;
end;

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

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

function StrawMod:onDeactivate()
    self.isTurnedOn = false;
end;

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

function StrawMod:objectInRange(refNode)
    local nearestDistance = 8;
    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 getUserAttribute(itemNode, "isStrawbale") or getUserAttribute(itemNode, "isHaybale") 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;