-- RepairCar specialization by rafftnix
-- @author: rafftnix
-- @date: 05.08.2012 
-- History: 
--          v1.0: initial Version (September 2012) 
-- Änderungen am Skript nur mit meiner Zustimmung!
-- Modification only with my permission!

RepairCar = {};

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

function RepairCar:load(xmlFile)
	self.repairVehicles = SpecializationUtil.callSpecializationsFunction("repairVehicles"); 
	self.repairCostsMultiplicator = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.repair#repairCostsMultiplicator"), 1);
	self.repairDistance = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.repair#repairDistance"), 15);
	self.currentRepairPrice = 0;
end;

function RepairCar:delete()

end;

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

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

function RepairCar:update(dt)
	if self:getIsActiveForInput() then
		if InputBinding.hasEvent(InputBinding.REPAIR_VEHICLES) then
			self:repairVehicles();
		end;
	end;
end;

function RepairCar:updateTick(dt)
	local price = 0;
	local meX, meY, meZ = getWorldTranslation(self.rootNode);
	for a=1, table.getn(g_currentMission.vehicles) do
		local vehicle = g_currentMission.vehicles[a];
		local vehicleX, vehicleY, vehicleZ = getWorldTranslation(vehicle.rootNode);
		if Utils.vector2Length(meX-vehicleX, meZ-vehicleZ) < self.repairDistance and vehicle.priceAtShop ~= nil and vehicle.damageLevel ~= nil then
			price = price + ((vehicle.priceAtShop * 0.0005 * self.repairCostsMultiplicator) * vehicle.damageLevel);
		end;
	end;
	self.currentRepairPrice = price + (price * (g_currentMission.missionStats.difficulty * 0.25)) * 5;
end;

function RepairCar:repairVehicles(calledByEvent)
	if self.isServer then
		local price = 0;
		local meX, meY, meZ = getWorldTranslation(self.rootNode);
		for a=1, table.getn(g_currentMission.vehicles) do
			local vehicle = g_currentMission.vehicles[a];
			local vehicleX, vehicleY, vehicleZ = getWorldTranslation(vehicle.rootNode);
			if Utils.vector2Length(meX-vehicleX, meZ-vehicleZ) < self.repairDistance and vehicle.priceAtShop ~= nil and vehicle.damageLevel ~= nil then
				price = price + ((vehicle.priceAtShop * 0.0005 * self.repairCostsMultiplicator) * vehicle.damageLevel);
				vehicle:setDamageLevel(0); 
			end;
		end;
		local totalRepairCosts = math.floor((price + (price * (g_currentMission.missionStats.difficulty * 0.25)) * 5));
		g_currentMission:addSharedMoney(-totalRepairCosts, "other");
	elseif not calledByEvent then
		RepairVehiclesEvent.sendEvent(self);
	end;
end;

function RepairCar:draw()
	if self.currentRepairPrice > 0 then
		g_currentMission:addHelpButtonText(g_i18n:getText("REPAIR_VEHICLES").." ("..g_i18n:getText("costs")..": "..tostring(math.floor(self.currentRepairPrice))..")", InputBinding.REPAIR_VEHICLES);
	end;
end;