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

defaults =
	client_id		: '1d04f85089fd4d44afd94f067ac3ce6c' #blogvio_client_id
	redirect_uri : 'https://widgetic.com/services/instagram/auth_token'
	scope				: 'basic'
	response_type: 'token'
	token				: localStorage.getItem 'instagramAuthToken'
	api_url			: 'https://widgetic.com/services/instagram'

api = window.INSTAGRAM_SERVICE_CONFIG || defaults

class InstagramService extends Service
	@browser: 'browser/controller/instagram'
	auth_url: "https://instagram.com/oauth/authorize/?client_id=#{api.client_id}&redirect_uri=#{api.redirect_uri}&response_type=#{api.response_type}&scope=#{api.scope}"

	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) ->
		if api.token?
			@getUser(api.token)
				.then (result) =>
					@user = result
					@trigger 'auth', @authenticated = true
				.catch => @deauth()

		!@authenticated and interactive and @doAuth()

	doAuth: ->
		window.instagramReady = (token, user) =>
			localStorage.setItem 'instagramAuthToken', api.token = token
			@user = user
			@trigger 'auth', @authenticated = true

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

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

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

module.exports = InstagramService
