Control  = require './index'
prevent = -> false

class DropDown extends Control
	className: 'control control-dropdown'
	template : 'core/views/dropdown'
	type: 'dropdown'

	elements:
		'.input-dropdown'             : 'input'
		'.input-dropdown-default span': 'default'
		'.input-dropdown-list'        : 'list'
		'.input-dropdown-list li'     : 'items'

	events:
		'mousedown .input-dropdown'     : prevent
		'mousedown .input-dropdown-list': prevent
		'click .input-dropdown'         : '_onClick'

	constructor: ->
		super
		@$window.bind('resize', @reposition).bind 'mousewheel scroll', @blur
		@updateOptions @options

	_onClick: =>
		@[if @list.is ':visible' then '_onBlur' else '_onFocus']()

	_onBlur: =>
		@list.hide()

	_onFocus: =>
		@reposition().show()
		@delay => $(@window.document).on 'click', @blur

	render: ->
		super

		@items.bind 'mousedown', @click
		@change @item?[@attribute] or @options.default, silent: true
		@reposition()
		(@body = $ @window.document.body).append @list

		@

	calculateDimensions: =>
		@elHeight   = @el.height()
		@listHeight = @list.height()
		@inputWidth = @input.width()
		@offset     = @el.offset()
		@offset.bottom = @offset.top + @elHeight + @listHeight - @$window.scrollTop()

	reposition: =>
		@calculateDimensions()
		top  = if @offset.bottom > @$window.height() then @input.offset().top - @listHeight else @offset.top + @elHeight - 1
		left = @offset.left
		width= @inputWidth - 2

		@list.css {top, left, width}

	update : (item, type, options={}) =>
		return @ if options.from and options.from is @
		@change @item?[@attribute], silent: true

	change:	(value) ->
		super
		return unless value?

		valRegEx = ///^#{value+''}$///ig
		return unless selectedOption = @options.options.filter((i) -> valRegEx.test i.value+'')[0]
		@default.text selectedOption.label
		@list.find("[data-value='#{selectedOption.value}']").addClass('active').siblings().removeClass 'active'

	click: (e) =>
		($target = $ e.target).addClass('active').siblings().removeClass 'active'
		@change $target.attr 'data-value'
		@blur()
		false

	disable: =>
		@$addClass('disabled').default.text @options.disabledText

	enable: =>
		@$removeClass('disabled').change @item?[@attribute] or @options.default or @options.options[0]?.value

	deactivate: => @blur()

	blur: =>
		$(@window.document).unbind 'click', @blur
		@_onBlur()

	focus: => @_onFocus()

	updateOptions: (options) =>
		@options = $.extend {}, @options, options
		@list.remove()
		@render @_onBlur()
		# set as disabled if only there's only 1
		@el.toggleClass 'disabled', @options.options.length <= 1

module.exports = DropDown
