Animation = {}

function Animation:new(anim_data,speed)
	local o = {}

	o.path = anim_data.path
	o.frames = anim_data.frames
	o.imgs = anim_data.imgs
	o.subframe = 0
	o.frame = 1
	o.speed = speed or 1

	o.was_updated = false

	setmetatable(o, self)
	self.__index = self
	return o
end

function Animation:getCenteredOffset()
	return self.imgs[1]:getWidth()/2, self.imgs[1]:getHeight()/2
end

function Animation:change(anim_data)
	if anim_data.path == self.path
	then
		return self
	else
		return Animation:new(anim_data)
	end
end

-- to manually handle what frame
function Animation:drawFrame(frame, x, y, rotate, sx, sy)
	if frame > #self.frames then
		frame = #self.frames
	end
	local x = x or 0
	local y = y or 0
	local sx = sx or 1
	local sy = sy or 1
	love.graphics.draw(
		self.imgs[frame],
		math.floor(x - Camera.pos.x),
		math.floor(y - Camera.pos.y),
		rotate,
		sx,
		sy
	)
end

-- to linearly animate
function Animation:animate()
	if self.was_updated then
		self.was_updated = false
	end
	if self.frames[self.frame] ~= 0 then
		-- try to animate
		self.subframe = self.subframe + self.speed

		if self.subframe > self.frames[self.frame]*game.framerate then
			self.subframe = self.subframe - self.frames[self.frame]*game.framerate
			self.frame = self.frame + 1
			self.was_updated = true
		end

		-- cycle
		if self.frame >= #self.frames+1 then
			self.frame = self.frame - #self.frames
		end
	end
end

-- to draw the current frame
function Animation:draw(x, y, rotate, sx, sy)
	local x = x or 0
	local y = y or 0
	local sx = sx or 1
	local sy = sy or 1
	love.graphics.draw(
		self.imgs[self.frame],
		math.floor(x),
		math.floor(y),
		rotate,
		sx,
		sy
	)
end
