Service = require '../../../browser/model'

host = 'https://widgetic.com'
INSTAGRAM_DEFAULTS = {
    client_id:      '542808610040105',
    client_secret:  '0a88504381f577dbbef400d4232a4258',
    redirect_uri:   host + '/services/instagram/auth_token',
    scope: 			'user_profile,user_media',
    response_type:	'code',
    api_url: 		host + '/services/instagram/',
    demo:           "IGQVJVNUw5cHB5cUFiZATFxVmgyeWtSVFJjTDYyRmNnWDZAJZA3llVXREa1BsS1EtVGJ2UEdlbHJNbDV1UUQ2YkVSZA3YwS1dPWXJzYXFGQzdZAMlhBLTBWWWNkTVNHTGNDLW10dkdhNW0wMDVqMkhZAWEhqbgZDZD",
    token_storage:  "redis",
    encodeToken:    false,
    redis_db:       0,
    redis_prefix:   "nstgrm:",
    port:           8082,
}
api = window.INSTAGRAM_SERVICE_CONFIG || INSTAGRAM_DEFAULTS
console.log("EDITOR Instagram API:", api);
api.token = localStorage.getItem 'instagramAuthToken'
auth_url =  "https://api.instagram.com/oauth/authorize/?client_id=#{api.client_id}&redirect_uri=#{api.redirect_uri}&response_type=#{api.response_type}&scope=#{api.scope}"

class InstagramService extends Service
	@browser: 'browser/controller/instagram'

	constructor: ->
		super
		@user = {}
		@authenticated = false

	getToken: ->
		return api.token

	getUser: (token) ->
		url = "#{api.api_url}/me"
		$.ajax(url: url, type: 'GET', dataType: 'json', headers: {'X-Token': token})

	_auth: (interactive=true) ->
		# console.log("Editor ISTG service _auth method:", interactive, api);
		if api.token?
			@getUser(api.token)
				.then (result) =>
					console.log("getUser result:", result)
					@user = result
					@trigger 'auth', @authenticated = true
				.catch => @deauth()

		!@authenticated and interactive and @showAuthPopup()

	showAuthPopup: ->
		# console.log("Editor show Auth Window:", localStorage, auth_url)
		
		window.instagramReady = (token, user) =>
			console.log("Editor instagramReady:", token, user);
			localStorage.setItem 'instagramAuthToken', api.token = token
			@user = user
			@trigger 'auth', @authenticated = true

		window.open auth_url, 'Instagram connect', 'width=450,height=600'

	refresh: (@entry) =>
		@trigger 'refresh', []

	deauth: ->
		@authenticated = false
		api.token = null
		@trigger 'auth', @authenticated
		localStorage.removeItem 'instagramAuthToken'

module.exports = InstagramService
