readyDef = new $.Deferred
readyPromise = readyDef.promise()

class FontLoader
	fontList: {}

	constructor: ->
		@loadFontLoader()

	loadFontLoader: ->
		wf = document.createElement 'script'
		wf.src = 'https://ajax.googleapis.com/ajax/libs/webfont/1.6.16/webfont.js'
		wf.type = 'text/javascript'
		wf.async = 'true'
		wf.onload = -> readyDef.resolve()
		s = document.getElementsByTagName('script')[0]
		s.parentNode.insertBefore(wf, s)

	load: (options = {}, context = window, source) -> readyPromise.then ->
		fontFamily = options.families[0]

		source or= options.source or 'google'
		if context.fontDefs? and context.fontDefs[fontFamily]?
			return context.fontDefs[fontFamily]

		context.fontDefs or= {}
		if source is 'local'
			return context.fontDefs[fontFamily] = (new $.Deferred).resolve().promise()

		context.fontDefs[fontFamily] = fl.loadGoogleFont options, context

	loadGoogleFont: (options, context) =>
		def = new $.Deferred
		WebFont.load
			google: options
			context: context
			fontactive: do (def) -> -> def.resolve arguments
			fontinactive: do (def) -> -> def.resolve arguments
			timeout: 600

		return def.promise()

	loadFontList: =>
		return @fontListRdy if @fontListRdy?
		def = Blogvio.Aye.defer()
		@_getFontList().then =>
			def.resolve $.extend {}, (f for _, f of @fontList)...
		@fontListRdy = def.promise

	_getFontList: =>
		def = new $.Deferred
		rdy = (source, fonts) ->
			if source
				fonts[font].source = source for font, opts of fonts
				@fontList[source] = fonts
			else
				@fontList = $.extend {}, @fontList, fonts
			def.resolve() if @fontList.google? and @fontList.local?

		$.getJSON('/fonts-list').then rdy.bind @, null
		$.getJSON('/fonts.json').then rdy.bind @, 'local'

		return def.promise()

module.exports = fl = new FontLoader