Controller  = window.require 'spine/controller'

FontList    = require './font-list'
Dropdown    = require '../dropdown'
Stepper     = require '../stepper'

{ createPopup } = require '../../utils/popup'

class FontPopup extends Controller
	template: 'core/views/font/fonts-popup'
	elements:
		'.font-list-wrapper': 'fontListEl'
		'.font-size': 'fontSizeEl'
		'.font-weight' : 'fontWeightEl'

	constructor: ->
		super
		@el.hide()

	render: ->
		super
		@el.toggleClass 'no-size-input', @disableSize
		@fontList = new FontList
			el: @fontListEl
			attribute: 'family'
			options: @options

		@fontSizeControl = new Stepper
			body: $ @popup.window.document.body
			el: @fontSizeEl
			attribute: 'size'
			options: $.extend label: 'Size', @options.size

		defaultStyle = @options.default?.style or @options.style
		@fontWeightControl = new Dropdown
			el: @fontWeightEl
			attribute: 'style'
			options:
				label: 'Style'
				default: defaultStyle
				options:[label: defaultStyle, value: defaultStyle]

		@listenTo @fontList, 'change', @_change
		@listenTo @fontSizeControl, 'change:stepper', @_change
		@listenTo @fontWeightControl, 'change:dropdown', @_change

	_change: (options) =>
		@trigger "change", options

	update: (item, type, options={}) =>
		@item = item if item
		return unless @popupPromise
		@fontList.update family: @item.family, type, options
		@fontSizeControl.update size: @item.size, type, options

		return if !@fontList.selected or @family is @item.family
		fontData = @fontList.getFontData(@family = @item.family) or {styles: [@item.style]}
		@fontWeightControl.updateOptions
			default: fontData.styles[0]
			options: fontData.styles[0...6].map (style) -> label:style, value:style

	_createPopup: ->
		return @popupPromise if @popupPromise
		@popupPromise = createPopup
				anchor: @popupReference
			.then (@popup) =>
				@el.show()
				@popup.append @el
				@render()
				@update @item, null, silent: true

			.catch (err) ->
				console.error err

	toggle: => @_createPopup().then =>
		if @popup?.visible then @deactivate() else @activate()

	activate: =>
		@popup?.show()
		@fontList.refresh()

	deactivate: =>
		@popup?.hide()

	release: ->
		@popup?.release()
		super

	setPopupTargetWindow: (@targetWindow) => @

module.exports = FontPopup
