--
-- sprayTankerTrigger
--
-- @author:    	Xentro (www.fs-uk.com)(Marcus@Xentro.se)
-- @version:    v1.0
-- @date:       2013-06-15
-- 
--[[
<sprayTrigger index="" />
]]--

sprayTankerTrigger = {};

function sprayTankerTrigger.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Sprayer, specializations);
end;

function sprayTankerTrigger:load(xmlFile)
	self.sprayTriggerCallback = sprayTankerTrigger.sprayTriggerCallback;
	self.fillSprayer = sprayTankerTrigger.fillSprayer;
	self.getIsActivatable = sprayTankerTrigger.getIsActivatable;
	
	local sprayTrigger = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.sprayTrigger#index"));
	
	if sprayTrigger ~= nil then
		self.sprayTrigger = sprayTrigger;
		addTrigger(self.sprayTrigger, "sprayTriggerCallback", self);
	end;
end;

function sprayTankerTrigger:delete()
	if self.sprayTrigger ~= nil then
		removeTrigger(self.sprayTrigger);
	end;
end;

function sprayTankerTrigger:readStream(streamId, connection)
end;

function sprayTankerTrigger:writeStream(streamId, connection)
end;

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

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

function sprayTankerTrigger:update(dt)
end;

function sprayTankerTrigger:updateTick(dt)
end;

function sprayTankerTrigger:draw()
end;

function sprayTankerTrigger:sprayTriggerCallback(triggerId, otherId, onEnter, onLeave, onStay, otherShapeId)
	if onEnter or onLeave then
		local sprayer = g_currentMission.objectToTrailer[otherShapeId];

		if sprayer ~= nil and sprayer ~= self and sprayer.addSprayerFillTrigger ~= nil and sprayer.removeSprayerFillTrigger ~= nil then
			if onEnter then
				sprayer:addSprayerFillTrigger(self);
			else
				sprayer:removeSprayerFillTrigger(self);
			end;
		end;
	end;
end;

function sprayTankerTrigger:fillSprayer(sprayer, delta)
	local deltaFillLevel = self:getFillLevel(self.currentFillType);
	
	if deltaFillLevel > 0 then
		delta = math.min(delta, deltaFillLevel);
		if delta <= 0 then
			return 0;
		end
	else
		return 0;
	end;
		
	if not sprayer:allowFillType(self.currentFillType, false) then
		return 0;
	end;
	
	if delta > 0 then
		local oldFillLevel = sprayer:getFillLevel(self.currentFillType);
		sprayer:setFillLevel(oldFillLevel + delta, self.currentFillType, true);
		delta = sprayer:getFillLevel(self.currentFillType) - oldFillLevel;
		
		self:setFillLevel(self.fillLevel - delta, self.currentFillType);
	end;
	
	return delta;
end;

function sprayTankerTrigger:getIsActivatable(fillable)
	if not fillable:allowFillType(self.currentFillType, false) or (self.fillLevel <= 0) then
		return false;
	end;
	
	return true;
end;