Control     = require '../index'
Container   = window.require 'spine/controller/container'
Stepper     = require '../stepper'

FontsPopup  = require './fonts-popup'

class FontControl extends Control
	@include Container
	template : 'core/views/font'
	className: 'control-font'

	elements:
		'.font-size': 'fontSizeEl'
		'.input-text': 'fontFamily'
		'.font-family-icon':'icon'
		'.font-popup':'popupEl'

	events:
		'click .font-family': 'toggle'

	render: =>
		super
		@lastVal or= family: @options.family, size: (@options.size.default or 0), style: @options.style

		@fontSizeControl = new Stepper
			el: @fontSizeEl
			attribute: 'size'
			options: @options.size

		@fontsPopup = new FontsPopup {el: @popupEl, @options, popupReference: @icon, default: @lastVal, disableSize: !@options.size}

		@listenTo @fontSizeControl, 'change:stepper', @_change
		@listenTo @fontsPopup, 'change', @_change

		@el.toggleClass 'no-size-input', !@options.size
		@delay => @update @item

	update: (item, type, options={}) =>
		return unless item[@attribute]
		# get the attribute by value
		@lastVal = $.extend {}, item[@attribute]

		options = $.extend {}, options, silent: true
		@fontsPopup.update @lastVal, type, options
		@fontSizeControl.update size: @lastVal.size, type, options
		@fontFamily.text @lastVal.family

	_change: (options) =>
		if options.attributes
			@lastVal[attr] = val for attr, val of options.attributes

		if options.attribute
			@lastVal[options.attribute] = options.value

		@change @lastVal

	toggle: =>
		@fontsPopup.toggle()

	deactivate: =>
		@fontsPopup.deactivate()

	setPopupTargetWindow: (targetWindow) =>
		@fontsPopup.setPopupTargetWindow targetWindow

module.exports = FontControl
