--***********************************************************
--**                    THE INDIE STONE                    **
--***********************************************************

require "TimedActions/ISBaseTimedAction"

ISTakeGasolineFromVehicle = ISBaseTimedAction:derive("ISTakeGasolineFromVehicle")

function ISTakeGasolineFromVehicle:isValid()
--	return self.vehicle:isInArea(self.part:getArea(), self.character)
	return true;
end

function ISTakeGasolineFromVehicle:update()
	self.character:faceThisObject(self.vehicle)
	self.item:setJobDelta(self:getJobDelta())
	self.item:setJobType("Take Gasoline")
	local litres = self.tankStart + (self.tankTarget - self.tankStart) * self:getJobDelta()
	if isClient() then
		if math.floor(litres) ~= self.amountSent then
			local args = { vehicle = self.vehicle:getId(), part = self.part:getId(), amount = litres }
			sendClientCommand(self.character, 'vehicle', 'setContainerContentAmount', args)
			self.amountSent = math.floor(litres)
		end
	else
		self.part:setContainerContentAmount(litres)
	end
	local usedDelta = self.itemStart + (self.itemTarget - self.itemStart) * self:getJobDelta()
	self.item:setUsedDelta(usedDelta)
end

function ISTakeGasolineFromVehicle:start()
	if self.item:getType() == "EmptyPetrolCan" then
		self.character:getInventory():DoRemoveItem(self.item)
		self.item = self.character:getInventory():AddItem("Base.PetrolCan")
		self.item:setUsedDelta(0)
	end
	self.tankStart = self.part:getContainerContentAmount()
	self.itemStart = self.item:getUsedDelta()
	local add = (1.0 - self.itemStart) * Vehicles.JerryCanLitres
	local take = math.min(add, self.tankStart)
	self.tankTarget = self.tankStart - take
	self.itemTarget = self.itemStart + take / Vehicles.JerryCanLitres
end

function ISTakeGasolineFromVehicle:stop()
	self.item:setJobDelta(0)
	ISBaseTimedAction.stop(self)
end

function ISTakeGasolineFromVehicle:perform()
	self.item:setJobDelta(0)
	if isClient() then
		local args = { vehicle = self.vehicle:getId(), part = self.part:getId(), amount = self.tankTarget }
		sendClientCommand(self.character, 'vehicle', 'setContainerContentAmount', args)
	else
		self.part:setContainerContentAmount(self.tankTarget)
	end
	print('take fluid level=' .. self.part:getContainerContentAmount() .. ' usedDelta=' .. self.item:getUsedDelta())
	-- needed to remove from queue / start next.
	ISBaseTimedAction.perform(self)
end

function ISTakeGasolineFromVehicle:new(character, part, item, time)
	local o = {}
	setmetatable(o, self)
	self.__index = self
	o.character = character
	o.vehicle = part:getVehicle()
	o.part = part
	o.item = item
	o.maxTime = time
	return o
end

