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

# Instagram service config
host = 'https://widgetic.com' + '/services/instagram/'
INSTAGRAM_DEFAULTS = {
    client_id:      '542808610040105', #widgetic instagram basic display app id
    client_secret:  '0a88504381f577dbbef400d4232a4258',
    redirect_uri:   host + 'auth_token',
    scope: 			'user_profile,user_media',
    response_type:	'code',
    api_url: 		host,
    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);
try 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}"

month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

cache =
	_cache: {}
	def: -> new $.Deferred()
	has: (id) -> cache._cache[id]?
	get: (id) -> cache.def().resolve(cache._cache[id]).promise()
	set: (id, data) -> cache._cache[id] = data; cache

class InstagramService extends Service

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

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

	_auth: (interactive=true) ->
		# console.log("Editor INSTG service _auth method:", interactive, api);
		# if authenticated get user info to show it in the browser
		if api.token?
			@getUser(api.token)
				.then (result) => 
					# console.log("Editor getUser result:", result)
					@user = result
					# @trigger 'auth', @authenticated = result.meta.code is 200
					@trigger 'auth', @authenticated = true
				.catch (error) => 
					# console.log("Editor getUser error:", error)
					@deauth()
		
		# console.log("Editor INSTG service _auth method:", interactive, api);
		# if not authenticated open popup
		!@authenticated and interactive and @showAuthPopup()

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

		window.open auth_url, 'Instagram connect', 'width=450,height=600'
	
	deauth: ->
		@authenticated = false
		api.token = null
		@trigger 'auth', @authenticated
		try localStorage.removeItem 'instagramAuthToken'


	# after response from the instagram popup
	refresh: (@entry) =>
		# console.log("Instagram Refresh:", @entry)
		# @entry.root = false
		@entry.children = []
		@children = {}
		@fetchFotos().done @_onRespond

	###
		Fetch Photos:
		return cache, if there's a cached response,
		but do the ajax too, so we can update the cache in the same time
	###
	fetchFotos: (id = '') =>
		url = "#{api.api_url}?num=999&q=#{@user.id}&max_id=#{id}"
		# console.log("fetchFotos 1:", api.token)
		# $.ajax {url: ..., type: ..., dataType: ...} {sucess: ...} {fail: ...}
		@ajaxReqs[id] = $.ajax
			url: url, type: 'GET', dataType: 'json', headers: {'X-Token': api.token}
			success: (data) => 
				# console.log("Fetch photos sucess:", data)
				cache.set(id, data)
			fail: (error) => 
				console.log("Fetch photos failed:", error)
		
		# console.log("fetchFotos 2:", api.token)
		if cache.has(id) then cache.get(id) else @ajaxReqs[id]

	_onRespond: (response) =>
		# filter data on image type
		data = response.media.filter (i) => (i.type = i.media_type.toLowerCase()) in @options.types
		# console.log("_onRespond filtered data:", data);

		# create folders or just list items
		# data = if @entry.root then @makeFolders(data) else @listEntries(data)
		data = @listEntries(data)
		# console.log("_onRespond organized data:", data);

		# add this new items to the content model
		@entry.children = @entry.children.concat data

		# trigger refresh for the widget to catch the content changes
		@trigger 'refresh', data

		# auto-fetch the next page of items, if there are any
		return unless next = response.pagination?.next_max_id
		@fetchFotos(next).done @_onRespond

	makeFolders: (data) =>
		folders = {}
		for item in data
			date = new Date(item.timestamp)
			folder_name = month[date.getMonth()]+' '+date.getFullYear()
			# don't create a new folder, if it's already defined
			# this could happen because of the multiple requests
			continue if (f for f in @entry.children when f.name == folder_name).length
			folders[folder_name] = new Entry
				service: @
				name: folder_name
				path: '/'+folder_name
				type: 'folder'
				year: date.getFullYear()
				month: date.getMonth()

		folder for name, folder of folders

	listEntries: (data) =>
		entries = [];
		for item in data 
			# if !@children[item.id]
			opts = {
				id: item.id, type: item.type, 
				media_url: item.media_url, 
				thumbnail_url: item.thumbnail_url,
				caption: item.caption,
				images: {image: item.media_url, thumbnail: item.thumbnail_url}
			}
			opts.videos = item.videos if item.videos?
			opts.path = @entry.path+'/'+item.id
			@children[item.id] = new Entry opts
			entries.push(@children[item.id])
		return entries

	preview: (entry) -> entry.images.image || entry.images.thumbnail

	getURL: (entry, callback)-> callback entry[entry.type+'s'].image

module.exports = InstagramService
