Panel = require './panel'

Activateable = window.require 'spine/controller/activateable'

_throttle =  (fn, delay) -> t = 0; cancel = false; (args...) ->
	return if cancel
	cancel = true
	fn args...
	setTimeout (-> cancel = false), delay

class PixelPanel extends Panel
	@include Activateable

	isMouseDown: false

	constructor: ->
		super
		@dragMove = _throttle @dragMove, 15

		@dragEvents =
			if !@isTouch
				'mousemove': @dragMove , 'mouseup': @stopDrag
			else 'touchmove': @dragMove, 'touchend': @stopDrag

	stopDrag: (e) =>
		@isMouseDown = false
		@document.unbind @dragEvents
		@update()

	startDrag: (e) =>
		@isMouseDown = true
		@prevent(e)
		@dragMove(e)
		@document.bind @dragEvents

	dragMove: (e) =>
		x = Math.max(0, Math.min(e.pageX - @offset.left, @maxWidth))
		y = Math.max(0, Math.min(e.pageY - @offset.top, @maxHeight))

		x = Math.ceil(@maxX*x/@maxWidth)
		y = Math.ceil(@maxY*y/@maxHeight)
		@update {x, y, @reference}
		@change()

	refresh: =>
		super
		@dragPanel.unbind 'mousedown', @startDrag
		@dragPanel.bind 'mousedown', @startDrag

	mouseEnterBody: (e) =>
		return unless @isMouseDown
		@stopDrag e if (e.buttons || e.which) isnt 1

module.exports = PixelPanel
