--
-- OperatingHours
-- Specialization for counting the operating hours of a vehicle
--
-- @author:  	Manuel Leithner
-- @date:		29/08/10
-- @version:	v2.0
-- @history:	v1.0 - initial implementation
--				v2.0 - convert to LS2011 (Networksupport) and some bugfixes
--

OperatingHours = {};

function OperatingHours.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Motorized, specializations);
end;

function OperatingHours:load(xmlFile)

	self.addOperatingTime = SpecializationUtil.callSpecializationsFunction("addOperatingTime");
	self.operatingTime = 0;	
	self.ohX = Utils.getNoNil(getXMLFloat(xmlFile,  "vehicle.operatingHours#posX"), 0.7543);
	self.ohY = Utils.getNoNil(getXMLFloat(xmlFile,  "vehicle.operatingHours#posY"), 0.1715);
	self.yOffset = 0.0077;
	self.ohOverlay = Overlay:new("hudOHOverlay", Utils.getFilename("scripts/OperatingHours_hud.png", self.baseDirectory), self.ohX, self.ohY, 0.11855, 0.039525);	
end;

function OperatingHours:delete()
end;

function OperatingHours:readStream(streamId, connection)
	self:addOperatingTime(streamReadFloat32(streamId), true);
end;

function OperatingHours:writeStream(streamId, connection)
	streamWriteFloat32(streamId, self.operatingTime);
end;

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

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

function OperatingHours:update(dt)
end;

function OperatingHours:updateTick(dt)
    if self:getIsActive() or self.isHired then 
		self:addOperatingTime(dt);
	end;
end;

function OperatingHours:draw()
	
	local operatingHours = math.floor((self.operatingTime / 1000 / 60 / 60)*10) / 10;
	local hours = math.floor(operatingHours);
	local minutes = tostring(math.floor((operatingHours - hours)*10));
	
	self.ohOverlay:render();
	setTextAlignment(RenderText.ALIGN_RIGHT);
	setTextBold(true);	
	renderText(self.ohX+0.062, self.ohY+self.yOffset, 0.022, tostring(hours) .. ",");
	setTextColor(0.95,0,0,1);
	renderText(self.ohX+0.071, self.ohY+self.yOffset, 0.023, minutes);
	setTextColor(1,1,1,1);
	renderText(self.ohX+0.08, self.ohY+self.yOffset, 0.023, "h");
	setTextAlignment(RenderText.ALIGN_LEFT);
end;

function OperatingHours:addOperatingTime(addTime)
	
	local time = math.max(Utils.getNoNil(addTime, 0), 0);	
	self.operatingTime = self.operatingTime + time;	
	
	if self.operatingTime > (99999.9 * 1000 * 60 * 60) then
		self.operatingTime = 0;
	end;
end;

function OperatingHours:loadFromAttributesAndNodes(xmlFile, key, resetVehicles)	
	if not resetVehicles then
		local operatingTime = Utils.getNoNil(getXMLFloat(xmlFile, key .. "#operatingTime"), self.operatingTime) * 1000;
		self:addOperatingTime(operatingTime);
	end; 
    return BaseMission.VEHICLE_LOAD_OK;
end;

function OperatingHours:getSaveAttributesAndNodes(nodeIdent)
	local attributes = 'operatingTime="' .. tostring((self.operatingTime / 1000)) ..'"';
	return attributes, nil;
end;