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

api =
	client_id    : '1d04f85089fd4d44afd94f067ac3ce6c' #blogvio_client_id
	# client_id    : 'e0d34a73d0df4535ac942135d440fb57' #test_client_id
	redirect_uri : 'https://widgetic.com/connect/instagram'
	scope 		 : 'basic'
	response_type: 'token'
	token        : localStorage.getItem 'instagramAuthToken'
	api_url		 : 'https://api.instagram.com/v1/'

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
	auth_url: "https://instagram.com/oauth/authorize/?client_id=#{api.client_id}&redirect_uri=#{api.redirect_uri}&response_type=#{api.response_type}"

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

	refresh: (@entry) =>
		@entry.children = []
		@children = {}
		@fetchFotos().done @_onRespond

	preview: (entry) -> entry.images.thumbnail.url

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

	_auth: (interactive=true) ->
		if api.token?
			url = "#{api.api_url}users/self/media/recent?access_token=#{api.token}"
			$.ajax(url: url, type: 'GET', dataType: 'jsonp')
				.then (result) => @trigger 'auth', @authenticated = result.meta.code is 200
				.catch => @trigger 'auth', @authenticated = false

		!@authenticated and interactive and @doAuth()

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

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

	_onRespond: (response) =>
		data = response.data.filter (i) => i.type in @options.types
		data = if @entry.root then @makeFolders(data) else @listEntries(data)

		@entry.children = @entry.children.concat data
		@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(parseInt(item.created_time) * 1000)
			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) =>
		start = new Date(@entry.year, @entry.month)
		end = new Date @entry.year, @entry.month+1
		filter = (created)->
			created = new Date(parseInt(created) * 1000)
			(start <= created) and (created <= end)

		for item in data when (filter item.created_time) and !@children[item.id]
			opts = {type: item.type, images: item.images, id: item.id}
			opts.videos = item.videos if item.videos?
			opts.path = @entry.path+'/'+item.id
			@children[item.id] = new Entry opts

	###
		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}users/self/media/recent?access_token=#{api.token}&count=999&max_id=#{id}"
		@ajaxReqs[id] = $.ajax
			url: url, type: 'GET', dataType: 'jsonp'
			success: (data) => cache.set(id, data)
		if cache.has(id) then cache.get(id) else @ajaxReqs[id]

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

module.exports = InstagramService
