Control = require './'

min = Math.min
max = Math.max
round = Math.round
limiter = (v,minimum,maximum)-> max minimum, min(maximum, +v)
$body = $ 'body'

class Stepper extends Control
	className   : 'control control-stepper'
	template    : 'core/views/stepper'
	type 		: 'stepper'
	elements:
		'.control-input' : 'input'
	events:
		'mousedown .spinner-button'	: 'mousedown'
		'keydown input' 			: 'keydown'

	isMouseDown: false

	constructor : ->
		super

		@options.step    or= 1
		@options.max     or= 10
		@options.min     or= 0
		@options.default or= 0
		@options.unit    or= ''

		@change (@item?[@attribute] or @options.default or 0), silent:true

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

	limit: (value) ->
		limiter parseInt(value), @options.min, @options.max

	update: (item,type,options={})=>
		return if options.from and options.from is @
		value = parseInt(if item[@attribute]? then item[@attribute] else @options.default) or 0
		@change value, silent: true

	value: (val) ->
		return @input.val val if val?
		if isNaN v=parseInt @input.val() then +@lastValue else v

	change: (val, args...) ->
		@lastValue = @limit val
		super @lastValue, args...

		@value round(@lastValue) + @options.unit

	render:->
		@input.unbind('blur').unbind 'focus'
		super
		@input.bind 'blur': @blur, 'focus': @focus
		@change (@item?[@attribute] or @options.default or 0), silent:true
		@

	focus: =>
		@value parseInt @value()

	blur: => 
		@change v = @limit(parseFloat @value()), silent: @lastValue is v

	keydown: (e)-> @blur() if e.keyCode is 13

	incdec: (inc) ->
		@change @limit parseInt(@value()) + inc

	mousedown: (e) =>
		e.preventDefault()
		@isMouseDown = true
		clearInterval @interval
		($body = $ @el[0].ownerDocument.body)
			.one('mouseup', @stopoinc)
			.unbind('mouseenter', @mouseEnterBody)
			.bind 'mouseenter', @mouseEnterBody

		inc =  if $(e.target).hasClass('spinner-up') then 1  else -1
		@incdec inc

		incf = =>
			@incdec(inc)
			clearTimeout(@timeout)
			@interval = setInterval (=>@incdec inc), 100

		@timeout  = setTimeout(incf,300) 

	stopoinc: (e)=>
		@isMouseDown = false
		clearInterval @interval
		clearTimeout @timeout

module.exports = Stepper