Controller		= window.require 'spine/controller'
Activateable	= window.require 'spine/controller/activateable'
Container 		= window.require 'spine/controller/container'
Scrollable 		= require 'Core/controller/scrollable'

h = window.virtualDom.h
diff = window.virtualDom.diff
patch = window.virtualDom.patch
createElement = window.virtualDom.create

NavBar 			= require './navbar'

Intent 			= """
	<div class=\"browser-login\">
		<div class=\"browser-login-cont\">
			<div class=\"browser-login-message\">add content from your account</div>
			<div class=\"browser-login-button\"></div>
		</div>
	</div>"
	"""

stripFalse = (obj) ->
	for key, value of obj
		if value is false
			delete obj[key]
	return obj

class SocialBrowser extends Controller
	className: 'browser social-browser'

	@include Container
	@include Activateable
	@include Scrollable

	scrollOptions: {}

	events:
		'click .browser-login-button': 'auth'

	constructor: ->
		super
		@attribute = @options.attribute

		@service = new @Service @title, @options
		@serviceTitle or= @service.title
		@authenticated = false
		@el.attr { @authenticated }

		@nav = new NavBar disconnectBtn: true
		@intent = $ Intent
		@_dropdownDisplay = 'none'

		@el.addClass @title
		@render()

		@on('activate', @auth)
		@listenTo @service, 'auth', @onAuth
		@listenTo @nav,  'logout', @onLogout

	auth: (e) ->
		return true if @authenticated
		@service.auth e?.type is 'click'
		true

	onAuth: (@authenticated) =>
		@el.attr { @authenticated }
		@$trigger "editor:browser:auth", service: @Service.name, @authenticated

	onLogout: =>
		@service.deauth()

	render: ->
		if !@rootNode
			@tree = @_render()
			@rootNode = createElement(@tree)
		else
    	newTree = @_render();
    	patches = diff(@tree, newTree);
	    @rootNode = patch(@rootNode, patches);
	    @tree = newTree;
			@$('input').each (index, i) =>
				return unless @content[index]
				i.value = @content[index].value

		@delay => @tab.count @content.length

	_render: ->
		h('ul', [
			@content.map (i) => @['_render_' + i.type](i, @onItemUpdate(i), true)
			@['_render_' + @newItem.type](@newItem, @onItemCreate) if @newItem
			@_render_select()
		])

	_render_user_id: (i) ->
		@_render_input('@', i, null, true)

	_render_username: (i, callback, allowDelete) ->
		@_render_input('@', i, callback, allowDelete)

	_render_hashtag: (i, callback, allowDelete) ->
		@_render_input('#', i, callback, allowDelete)

	_render_input: (symbol, i, callback, allowDelete) ->
		h('li.directinput-field.social-browser__input', [
			h('div.control.control-url.social-browser__control', [
				h('span', symbol),
				h('input.control-input.input-text', {
					onblur: callback,
					attributes: stripFalse {
						type: 'text',
						placeholder: 'username',
						value: i.value
						readonly: !callback
					}
				})
			]),
			h('span.field-delete', {
				onclick: @onDeleteClicked(i),
				attributes: { 'data-icon': '⏍' }
			}) if allowDelete
		])

	_render_select: ->
		accountTypeItems = @content.filter (i) => i.type is 'user_id' and i.token is @service.getToken()
		accountNotConnected = accountTypeItems.length is 0
		h('li.social-browser__input',
			h('div.control.control-dropdown', [
				h('div.input-dropdown',
					h('div.input-dropdown-default', { onclick: @_toggleDropdown }, [
						h('span',	'Add'),
						h('div.dropdown-arrow')
					])
				),
				h('ul.input-dropdown-list',	{ style: { display: @_dropdownDisplay }}, [
					h('li',	{ onclick: @_addInput('user_id') },	'My account') if accountNotConnected,
					h('li', { onclick: @_addInput('username') }, 'Username'	),
					h('li',	{ onclick: @_addInput('hashtag') },	'Hashtag'	)
				])
			])
		)

	_toggleDropdown: =>
		@_dropdownDisplay = if @_dropdownDisplay is 'block' then 'none' else 'block'
		@render()

	_addInput: (type) => (e) =>
		@_toggleDropdown()

		@trigger 'canAdd', => @__addInput(type)

	__addInput: (type) ->
		@newItem = {}
		@newItem.service = @title
		@newItem.type = type
		@newItem.token = @service.getToken()

		if type is 'user_id'
			@newItem.id = @service.user.id
			@_add(@service.user.username)
		else
			@render()
			@$('input[type=text]:last').focus()

	onItemCreate: (e) =>
		val = e.currentTarget.value
		return unless val

		@_add(val)

	_add: (val) ->
		@newItem.value = val
		@newItem[@attribute] = @_attributeVal(@newItem)
		@trigger 'add', @newItem
		@newItem = undefined
		@render()

	_attributeVal: (item) -> 'Instagram: ' + (if item.type is 'hashtag' then '#' else '@') + item.value

	onItemUpdate: (item) => (e) =>
		val = e.currentTarget.value
		return unless val
		return unless val != item.value

		item.value = val
		item[@attribute] = @_attributeVal(item)
		@trigger 'update', item, @attribute, item[@attribute]

	onDeleteClicked: (item) => (e) =>
		@trigger 'remove', item
		@removeEntry(item)

	addEntry: (item) ->
		@content.push(item)
		@render()

	removeEntry: (item) ->
		return unless @content.indexOf(item) >= 0
		@content.splice @content.indexOf(item), 1
		@render()

	active: ->
		Activateable.active.apply @, arguments
		@scrollOptions.documentContext = @el.get(0).ownerDocument
		@scroll()
		@el.append @nav.el, @intent
		@append @rootNode
		@delay =>
			@$trigger 'editor:browser:active', service: @Service.name, @authenticated

	deactivate: =>
		Activateable.deactivate.apply @, arguments

module.exports = SocialBrowser
