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

LoginIntent = ->
	"""
	<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>"
	"""

LogoutIntent = (options = {}) ->
	"""
	<div class=\"browser-intent-logout\">
		<div class=\"browser-login-cont\">
			<!-- <img width="100" height="100" src="#{options.profile_picture}"/> -->
			<div class=\"browser-login-message\">You are connected as <strong style="font-size: 21px;">#{options.username}</strong></div>
			<div class=\"browser-login-button browser-logout-button\"></div>
		</div>
	</div>"
	"""

class InstagramBrowser extends Controller
	className: 'browser instagram-browser'

	@include Container
	@include Activateable

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

	constructor: ->
		super
		@service = new @Service @title, @options
		@serviceTitle or= @service.title

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

		@loginIntent = $ LoginIntent()
		@logoutIntent = $ LogoutIntent()

		@el.addClass @title

		@listenTo @service, 'auth', @onAuth

		# if there exists content created using this service,
		# use the first one as the connected account
		# (there should be only one, but just in case)
		@authenticated = !!@content.length
		console.log("Editor Instagram Browser @authenticated:", @authenticated, @content[0]);
		@el.attr {@authenticated}
		if @authenticated
			@connectedAccount = @content[0]
			# the content metadata stores the SHA256 hash of the user's Instagram token
			@service.getUser(@connectedAccount.token)
				.then((user) =>
					console.log("Editor Instagram Browser CT getUser result:", user)
					if(user.error) 
						# console.log("Editor Browser get inst user result:", user)
						# @onAuth(false);
						this._updateLogoutIntent(@connectedAccount)
					else 
						this._updateLogoutIntent(user)
				)
				.catch((err) => console.log("Editor Browser getUser err:", err))

	active: ->
		Activateable.active.apply @, arguments
		@el.append @loginIntent, @logoutIntent

		@delay =>
			@$trigger "editor:browser:active", service: @Service.name, @authenticated

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

	auth: (e) ->
		console.log("Editor Instagram Browser auth handler:", e, @authenticated);
		return if @authenticated
		@service.auth( e?.type is 'click')
		true

	onAuth: (@authenticated) =>
		console.log("Editor Instagram Browser onAuth:", @authenticated, @service.user)
		@el.attr {@authenticated}
		@$trigger "editor:browser:auth", service: @Service.name, @authenticated
		return unless @authenticated
		@_updateLogoutIntent(@service.user)

		item = {}
		item.service = @title
		item.token = @service.getToken()
		item.path = Math.random().toString()
		item.active = true
		item.type = 'user_id'
		item.id = @service.user.id
		item.url = 'Instagram User: @' + @service.user.username
		item.username = @service.user.username
		@connectedAccount = item
		@trigger 'add', item

	# called after 'add' event is processed by content panel
	addEntry: (entry) ->
		return if @content.indexOf(entry) isnt -1
		@tab.count @content.push entry

	onLogout: =>
		if @connectedAccount
			@trigger 'remove', @connectedAccount
			@removeEntry @connectedAccount

		@service.deauth()

	removeEntry: (entry) ->
		if @content.indexOf(entry) >= 0
			@content.splice @content.indexOf(entry), 1
		@tab.count @content.length

	_updateLogoutIntent: (user) ->
		# console.log("update logout intent:", user)
		@logoutIntent.remove()
		@logoutIntent = $ LogoutIntent user
		@el.append @logoutIntent

module.exports = InstagramBrowser
