Controller 		= window.require 'spine/controller'
Container  		= window.require 'spine/controller/container'
Activateable 	= window.require 'spine/controller/activateable'

Attributes 		= require './attributes'

class Item extends Controller
	className: 'item-details'
	tag:'li'
	@include Container
	@include Activateable
	elements:
		'.item-details-order':     'place'
		'.item-details-toggle':    'toggleButton'

	events:
		'click .item-details-toggle': 'toggle'
		'click .item-details-delete': 'destroy'
		'invalid':'_onItemValidation'
		'valid':'_onItemValidation'

	constructor: ->
		super
		@item.bind 'destroy', @release
		@item.bind 'change',  @_change

		order 		= "<div class='item-details-order'></div>"
		toggle 		= "<div class='item-details-toggle'></div>"
		idel 		= "<div class='item-details-delete' data-icon='⏍'></div>"
		right 		= $ "<div class='item-details-right'></div>"

		@attributes = new Attributes {options:@meta.attributes, @item}
		right.append toggle, idel
		@append order, @attributes, right

	_change : (item,type,options) =>
		return unless options.attribute is 'order'
		@place.html item.order

	activate: (options={})->
		return if @attributes.length < 2 or @isInvalid
		Activateable.activate.apply @,[options]

		@animateFirstAttribute() if options.animate
		@attributes.update()

	deactivate: ->
		Activateable.deactivate.apply @, arguments
		@attributes.deactivate()

	toggle: =>
		if @isActive() then @deactivate() else @activate()
		@parent().scroll().update()

	destroy:=> @item.destroy()

	# triggered by the item's main attribute
	_onItemValidation: (e) =>
		@isInvalid = e.type is 'invalid' and @attributes.el.children().first().is e.target
		@el.toggleClass 'item-invalid', @isInvalid
		@deactivate() if @isInvalid

	# on activation, slideDown the first @attribute
	animateFirstAttribute: ->
		# get the extended height
		h = @el.height()
		# set the animation start/ default min-height
		@el.height @el.css 'minHeight'
		# activate the transitions
		@el.addClass('transitions').on 'transitionend webkitTransitionEnd', (e) =>
			return unless $(e.target).is @el
			# remove the transitions and update the scrollbar
			@el.removeAttr('style').removeClass 'transitions'
			@parent().scroll().update()

			@el.off 'transitionend webkitTransitionEnd'
		.height h

	onDrop: ->
		@attributes.onDrop()

module.exports = Item
