Control = require './index'
###
Initialize with {item:{skin instance},attribute:'attribute',options:{options from meta}}
###
class TextArea extends Control
	className: 'control-textarea loading'
	template: 'core/views/textarea'
	parserRules:
		tags:
			b:{}, i:{}, u:{}, br: {}
			a:
				set_attributes:
					target: "_blank",
					rel:    "nofollow"
				check_attributes:
					href:   "url"

	elements:
		'textarea':'textarea'
		'.toolbar':'toolbar'

	update: (item, type, options={}) =>
		value = if item[@attribute]? then item[@attribute] else @options.default
		# console.log('TextArea update:', value)

		# return if no value or if wysihtml5 editor is not loaded
		return if !value or @loaded and (value is @editor.getValue())
 		# console.log('TextArea update:', value)
 		
		# set value in editor
		if @editor then @editor.setValue value


	render: =>
		@el.addClass 'loading'
		super

		return unless (_editor = @_editor())?
		@editor = new _editor @textarea[0], {
			@parserRules,
			placeholderText: @options.placeholder
			toolbar: @toolbar[0]
			style: true
		}
			.on('load',@_load)
			.on('change',@_change)

		@editor.on 'focus', (e) =>
			return if @el.is '.focused'
			@el.addClass 'focused'
			@editor.currentView.element.style.overflow = 'auto'

		@editor.on 'blur', (e) =>
			return unless @el.is '.focused'
			@el.removeClass 'focused'
			@editor.currentView.element.scrollTop = 0
			@editor.currentView.element.style.overflow = 'hidden'
		@

	onDrop: ->
		@editor?.stopObserving()
		@render()

	_load: =>
		@loaded = true
		@el.removeClass 'loading'

	_change: =>
		@change @editor.getValue()

	release: =>
		@editor?.stopObserving()
		super

	_editor: =>
		window.wysihtml5?.Editor

module.exports = TextArea
