Mouse = class("Mouse")

function Mouse:new()
	local e = instance(self)
	e.x = 10
	e.y = 10
	e.lastX = {}
	e.lastY = {}
	e.scaledDragX = 0
	e.scaledDragY = 0
	e.count = 0
	e.moved = false
	e.left = false
	e.right = false
	e.middle = false
	e.lastLeft = false
	e.lastRight = false
	e.lastMiddle = false
	e.clickX = 0
	e.clickY = 0
	e.eaten = false
	e.scrollUp = false
	e.scrollDown = false
	e.scrollSpeed = 1
	e.lastScroll = 0
	e.lastScrollDown = 0
	e.lastScrollUp = 0
	e.forceRight = false
	e.forceLeft = false
	e.screenX = 10
	e.screenY = 10
	e.time = 0
	e.mx = 0
	e.my = 0
	return e
end

function Mouse:onClick(x,y,button,clickCount)
	if not self.middle and (button == 4 or button == 3) then
		if self.lastScroll == 0 then
			self.lastScroll = self.time
		else
			local diff = self.time - self.lastScroll

			self.scrollSpeed = math.max(1,math.floor(5/(1+diff*25)))
			self.lastScroll = self.time
		end
		if button == 4 then
			self.scrollUp = true
			self.lastScrollUp = self.time
		elseif button == 3 then
			self.scrollDown = true
			self.lastScrollDown = self.time
		end
	end

	if button == 0 then
		self.forceLeft = true
	elseif button == 1 then
		self.forceRight = true
	elseif button == 2 then
		self.forceMiddle = true
	end
		
	self.count = clickCount
end

function Mouse:hasMoved()
	return self.moved
end

function Mouse:update(time)
	if self.activated then
		local nx,ny = daisy.getMousePosition()
		
		self.moved = false
		if nx ~= self.screenX or ny ~= self.screenY then
			local history = 20
			for i=1,history do 
				self.lastX[history-i+2] = self.lastX[history-i+1] or 0
				self.lastY[history-i+2] = self.lastY[history-i+1] or 0
			end
			self.moved =true
		end
		
		self.screenX = nx
		self.screenY = ny

		self.lastLeft = self.left
		self.lastRight = self.right
		self.lastMiddle = self.middle

		self.left = daisy.isMouseButtonPressed(0)
		self.right = daisy.isMouseButtonPressed(1)
		self.middle = daisy.isMouseButtonPressed(2)

		if self.forceLeft then
			self.left = true
			self.forceLeft = false
		end
		if self.forceRight then
			self.right = true
			self.forceRight = false				
		end

		if self.forceMiddle then
			self.middle = true
			self.forceMiddle = false	
		end
		
		self.eaten = false
		self.time = self.time + time
		self.scrolling = self.lastScroll >= self.time - 0.25
		self.scrollingUp = self.lastScrollUp >= self.time - 0.25
		self.scrollingDown = self.lastScrollDown >= self.time - 0.25
		return true
	else
		local nx,ny = daisy.getMousePosition()
		if nx >0 or ny >0  then
			self.activated = true
		end	
	end
end

function Mouse:set(x,y)
	self.lastX[1] = self.x or 0
	self.lastY[1] = self.y or 0
	self.x = x or self.screenX
	self.y = y or self.screenY
end

function Mouse:getMotionAngle()
	return math.angleBetweenPoints(self.lastX[#self.lastX], self.lastY[#self.lastY], self.x, self.y)
end

function Mouse:postUpdate(time)
	self.scrollUp = false
	self.scrollDown = false
	self.moved = false
end