--
-- FillLevel
-- Specialization for FillLevel
-- only for Filllevel.. no need of motorized specialization!
-- 
-- Date: 26.10.2015
-- Author: Unguided
-- free usage!

FillLevel = {};

function FillLevel.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(AnimatedVehicle, specializations);
end;

function FillLevel:load(xmlFile)
	
	self.sethudFillValue = FillLevel.sethudFillValue;
	 
	self.FillLevel = {};
	self.FillLevel.fillLevel = FillLevel.loadValue(self, xmlFile, "fillLevel");
end;

function FillLevel:loadValue(xmlFile, name)
    local numbers = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.FillLevel."..name.."#numbers"));
    local animName = getXMLString(xmlFile, "vehicle.FillLevel."..name.."#animName");

	if numbers ~= nil or animName ~= nil then
		local precision = nil;
		local numChilds = nil;
		local maxValue = nil;
		if numbers ~= nil then
			precision = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.FillLevel."..name.."#precision"), 1);
			numChilds = getNumOfChildren(numbers);
			if numChilds-precision <= 0 then
				print("Warning: Not enough number meshes in '"..self.configFileName.."'");
			end;
			numChilds = numChilds - precision;
			maxValue = (10 ^ (numChilds)) - 1/(10^precision);
		end;
		
		local hudFill = {numbers=numbers, animName=animName, lastNormValue=0, lastValue=-1, precision=precision, maxValue=maxValue, numChilds=numChilds};
		
		self:sethudFillValue(hudFill, 0, 0);
		
		return hudFill;
	end;
	
	return nil;
end;

function FillLevel:delete()
end;

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

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

function FillLevel:update(dt)	
end;

function FillLevel:updateTick(dt)
	if self:getIsActive() then
		if self.FillLevel.fillLevel ~= nil and self.fillLevel ~= nil and self.getCapacity ~= nil and self:getCapacity() ~= 0 then
        self:sethudFillValue(self.FillLevel.fillLevel, self.fillLevel, self:getCapacity());
		end;
	end;
end;
	
function FillLevel:draw()
end;

function FillLevel:sethudFillValue(hudFill, value, maxValue) 
	if hudFill.numbers ~= nil then
		if math.abs(hudFill.lastValue-value) > 1/(10^(hudFill.precision+1)) then
			local displayedValue = math.min(hudFill.maxValue, math.max(0, value));
			local speed = tonumber(string.format("%."..hudFill.precision.."f", displayedValue));
			Utils.setNumberShaderByValue(hudFill.numbers, speed, hudFill.precision, true);
			hudFill.lastValue = value;
		end;
	end;
	if hudFill.animName ~= nil then
		local normValue = Utils.round(value/maxValue, 3);
		if maxValue == 0 then
			normValue = 0;
		end;
		if math.abs(hudFill.lastNormValue - normValue) > 0.01 then
			self:setAnimationTime(hudFill.animName, normValue, true);
			hudFill.lastNormValue = normValue;
		end;
	end;
end;
