Controller      = window.require 'spine/controller'
Content         = window.require 'core/models/content'
AttributesPanel = require './attributes-panel'

class BulkEditor extends Controller
	className: 'details_bulk-editor activateable'

	elements:
		'.item-details': 'attributesEl'

	events:
		'click .item-toggle': 'toggle'

	_isActive: false

	template: ->
		"""
		<div class="bulk-editor-header">
			<div class="bulk-editor-title">#{@options.title}</div>
			<div class='item-details-right'>
				#{
					if @options.help_text
						'<div class="control-help" data-tooltip-text="'+@options.help_text+'"></div>'
					else ''
				}
				<div class="item-toggle multi-tabs-toggle" data-icon="❯">
					<span data-icon="❯"></span>
				</div>
			</div>
		</div>
		<div class="item-details"></div>
		"""

	toggle: =>
		# @attrPanel?.attributes.update()
		@_isActive = !@_isActive
		@trigger 'toggle', @_isActive
		@el.toggleClass 'active', @_isActive
		@attributesEl.css
			'margin-bottom': if @_isActive then 0 else -@attributesElHeight

	for: (@composition) =>
		return @el.addClass('empty') unless @composition.contentMeta().bulkEditor?

		@item = @composition.bulkContent()

		@item.bind 'change',  @_change
		@listenTo Content, 'create', @onItemAdded
		@listenTo Content, 'change', @onItemChange
		@initialize @composition.contentMeta()

	initialize: (contentMeta) =>
		@options = contentMeta.bulkEditor
		@render()

		@numAttributes = @options.attributes.length
		@el.toggleClass('single-attribute', @numAttributes is 1)

		for attr in @options.attributes
			(@attributes or= {})[attr] = contentMeta.attributes[attr]

		@attrPanel = new AttributesPanel {options: @attributes, @item, el: @attributesEl}
		@attributesElHeight = @attributesEl.outerHeight()

	_change: (item, evType, options)=>
		return if (attr = options.attribute) is 'metadata'
		@composition.getContent().forEach (c) =>
			return if c.id is @item.id or c.editedMeta attr
			c.attrMeta attr, false
			c.updateAttribute attr, @item[attr], attribute: attr, from: @

	onItemAdded: (item) =>
		return unless item.composition_id is @composition.id
		@updateItemAttributes Content.find item.id

	updateItemAttributes: (item) =>
		return unless item.composition_id is @composition.id
		for attr, _ of @attributes when !item.editedMeta(attr) and item[attr] isnt @item[attr]
			item.attrMeta attr, false, silent: true
			item.updateAttribute attr, @item[attr], attribute: attr, from: @

	onItemChange: (item, evType, options) =>
		return if options.attribute isnt 'metadata' or options.silent
		@updateItemAttributes c for c in @composition.getContent() when c.id is item.id

module.exports = BulkEditor
