Controller = window.require 'spine/controller'
Scrollable = require '../../controller/scrollable'
Lazyloader 		= require '../../controller/lazyload'

FontItem   = require './font-item'
FontLoader = require '../../controller/font-loader'

class FontList extends Controller
	@include Scrollable
	@include Lazyloader
	template: 'core/views/font/fonts-list'
	className: 'font-list-wrapper'
	scrollOptions: {}
	offsetToPreLoad: 250

	fonts: {}
	fontCtrls: {}

	elements:
		'.search-input':'searchInput'
		'.font-item': 'fontItems'
		'.font-list': 'scrollContainer'
		'.no-result': 'noResult'
		'.clear'    : 'clearBtn'

	events:
		'change input[type="radio"]': 'onInput'
		'keyup .search-input': 'onSearchInput'
		'click .clear': 'clearSearch'

	constructor: ->
		@fontCtrls = {}

		super
		@ready().then (@fonts) => @refresh @render()

	onInput: (e) =>
		attributes = {}
		attributes[@attribute] = font = $(e.target).val()
		attributes.style       = @fonts[font].styles[0]
		attributes.source      = @fonts[font].source
		attributes.category    = @fonts[font].category
		@trigger "change", {attributes}

	update: (item, type, options = {}) => @ready().then =>
		(opt = @el.find "[value=\"#{item[@attribute]}\"]").prop 'checked', true
		@selected = @fonts[item[@attribute]]
		# @scrollOnOpen opt

	onSearchInput: =>
		clearTimeout @int
		@int = @delay (=> @filter @searchInput.val()), 150

	filter: (filter) =>
		filter = filter.toLowerCase().replace /\ /g, ''

		unless filter
			@clearBtn.hide()
			@fontItems.show().first().hide()
			return do @refresh

		@clearBtn.show()
		resCount = @fontItems
			.filter(":not([data-tag*=#{filter}])").hide()
			.end()
			.filter("[data-tag*=#{filter}]").show()
			.length

		@noResult.toggle !resCount

		do @refresh

	clearSearch: =>
		@searchInput.val ''
		@onSearchInput()

	render: =>
		super
		@scrollOptions.documentContext = @el.get(0).ownerDocument

		for font, fontData of @fonts
			@scrollContainer.append (@fontCtrls[font] or= new FontItem font, fontData).el

		@refreshElements()

	refresh: => @ready().then =>
		do @scroll().update
		@lazyContainer = @scrollContainer.find '.scroll-content'
		do @lazyLoad

	ready: =>
		do FontLoader.loadFontList

	scrollOnOpen: (item) =>
		@refresh()
		@scroll().scrollTo item.parent() unless @first
		@first = true

	whileScrolling: =>
		do @lazyLoad

	lazyItems: =>
		@fontCtrls[_] for _, fontData of @fonts when @fontCtrls[_].el.is ':visible'

	getFontData: (font) =>
		@fonts[font]

module.exports = FontList
