DropdownControl = require './dropdown'

###
	---------------------------------------------------
	Meta
	---------------------------------------------------
	"default"   : {
		"play"     : {"enabled": true, "order": 1},
		"progress" : {"enabled": true, "order": 2},
		"time"     : {"enabled": true, "order": 3},
		"mute"     : {"enabled": true, "order": 4}
	},
	"options"   : [
		{"label":"Play/Pause","value":"play"},
		{"label":"Progress Bar","value":"progress"},
		{"label":"Time","value":"time"},
		{"label":"Mute/Unmute","value":"mute"}
	]
###
class OrderPicker extends DropdownControl
	template : 'core/views/order-picker'
	itemsTmpl: window.require 'core/views/order-items'
	className: 'order-picker'

	init: =>
		(@labels or= {})[opt.value] = opt.label for opt in @options.options

	constructor: ->
		super
		@sortable @list,
			itemSelector: ".list-item"
			handle:       ".item-details-order"
			onDragStart:  @onDragStart
			onDrop:       @onDrop
			onDrag:       @onDrag

		@list.bind 'change', @_change

	render:=>
		super
		@update @item if @item
		@default.text "Arrange Items"
		@

	onDragStart: (item, container, _super) =>
		@isDragging = true
		_super item, container

	onDrag: (item, position, _super) =>
		_super item, position

	onDrop: (item, container, _super) =>
		@isDragging = false
		_super item, container
		@_change()

	_change: =>
		value = {}
		@list.find('.list-item').each (i, o) ->
			item = ($o = $ o).data 'value'
			order = 1 + $o.index()
			enabled = $o.find('.is-enabled').is ':checked'
			value[item] = {order, enabled}

		@change value

	update: (item, type, options={}) =>
		return if @isDragging
		value = if item[@attribute]? then item[@attribute] else @options.default
		options = []
		for option in @options.options
			if value[option.value]
				order = value[option.value].order
				options[order - 1] = $.extend {order}, option, enabled: value[option.value].enabled

		# do a second pass for options that are not present in the skin
		# in cases where the skin was created before this option was added to the meta
		# include the new option but make it hidden
		for option in @options.options
			if !value[option.value]
				options.push $.extend {order: options.length}, option, enabled: false


		@list.html @itemsTmpl {options}

	sortable: (el, opts...) ->
		$(el).sortable opts...

	blur: (e) =>
		return if !e or e.type is 'click' and $(e.target).closest(@list).length
		super

module.exports = OrderPicker
