TweenManager = { tweens = {} }

function TweenManager.add(tween)
	table.insert(TweenManager.tweens, tween)
	print("tweenmanager", #TweenManager.tweens)
end

function TweenManager.remove(position)
	table.remove(TweenManager.tweens, position)
end

function TweenManager.update(time)
	local i
	
	i = 0
	--[[while i < #TweenManager.tweens do
		
		if TweenManager.tweens[i]:update() then
			i = i + 1
		else
			TweenManager.remove(i)
		end
	end]]--
	
	for index, value in ipairs(TweenManager.tweens) do
		print(index, value)--, value:update(time))
	end

end

Tween = {
	--[[valuesStart = {},
	valuesChange = {},
	valuesTo = {},
	duration = 1,
	delayTime = 0,
	startTime = nil,
	easing = nil,
	nextTween = nil,
	-- onUpdateFunction
	-- onCompleteFunction
	completed = false]]--
}
Tween_mt = { __index = Tween }

function Tween:new(object)
	o = {
		object = object,
		valuesStart = {},
		valuesChange = {},
		valuesTo = {},
		duration = 1,
		delayTime = 0,
		startTime = 0,
		easing = TweenEasing.Elastic.EaseIn,
		nextTween = nil,
		-- onUpdateFunction
		-- onCompleteFunction
		completed = false
	}
	setmetatable(o, self)
	self.__index = self
	--TweenManager.add(self)
	--print (self, o)
	TweenManager.add(o)
	return o
end

function Tween:to(duration, properties)
	for index, property in pairs(properties) do
		if self.object[property] ~= nil then
			self.valuesTo[property] = properties[property]
		end
	end
end

function Tween:start(time)
	self.completed = false
	self.startTime = time
	
	for index, property in pairs(self.valuesTo) do
		if self.object[property] ~= nil then
			self.valuesStart[property] = self.object[property]
			self.valuesChange[property] = self.valuesTo[property] - self.object[property]
		end
	end
end

function Tween:delay(time)
	self.delayTime = time
end

function Tween:update(time)
	local property, elapsed
	
	print('update', time, self.startTime)
	
	if time < self.startTime then --or self.startTime == nil then
		return true
	end
	
	if self.completed then
		return (self.nextTween == nil)
	end
	
	elapsed = time - self.startTime
	
	if elapsed > self.duration then
		self.completed = true
		self.startTime = nil
		
		return false
	end
	
	
	for index, property in pairs(self.valuesChange) do
	
		self.object[index] = self.easing(elapsed, self.valuesStart[index], self.valuesChange[index])
	end
	
	return true

end
	
TweenEasing = { Elastic = {} }	
	
function TweenEasing.Elastic.EaseIn( t, b, c, d )
	if ( t == 0 ) then
		return b
	end
	
	local tt = t / d
	
	if ( ( tt ) == 1 ) then
		return b + c
	end
	
	local p = d * 0.3
	local a = c
	local s = p / 4
	
	return - ( a * math.pow( 2, 10 * ( t - 1 ) ) * math.sin( ( t * d - s ) * ( 2 * math.pi ) / p ) ) + b
end


