--Exported


function module.new(sourceInstance, data, duration)
	
	local record = RecurseAdd(sourceInstance, data)
	local self = setmetatable(
		{
			record = RecurseAdd(sourceInstance, data),
			state = 0,
			duration  = duration
			
		}, module)
	
	
	return self
end


function RemoveTween(tweenRecord, instance)
	local sourceInstance = tweenRecord.sourceInstance
	if (instance) then
		sourceInstance = instance
	end

	for key,value in pairs(tweenRecord.pairs) do
		sourceInstance[key] = value.src		
	end
	for key,value in pairs(tweenRecord.children) do

		local child = tweenRecord.sourceInstance
		if (child) then
			RemoveTween(value, child)
		end
	end
end

function module:RemoveTween()
	RemoveTween(self.record)
end

function SetTween(tweenRecord, frac)

	for key,value in pairs(tweenRecord.pairs) do
		tweenRecord.sourceInstance[key] = value.func(value.src,value.dst, frac)		
	end
	for key,value in pairs(tweenRecord.children) do

		local child = tweenRecord.sourceInstance
		if (child) then
			SetTween(value, frac)
		end
	end
end

function module:SetTween(frac)
	
	frac = math.clamp(frac,0,1)
 	SetTween(self.record, frac)
end

function module:RunTween(deltaTime, grow)
	
		
	local oldFrac = self.state
	if (grow == true) then
		self.state += deltaTime / self.duration
	else
		self.state -= deltaTime / self.duration
	end
	self.state = math.clamp(self.state,0,1)

	if (oldFrac ~= self.state) then
		self:SetTween(self.state)
	end
	
end

return module
