Router = require 'core/router'

onResponse = (data) ->
	@constructor.defs[@_url] = @lastDef

	{data, pagination} = data
	@callback data
	@lastID = pagination.next_max_tag_id

class InstagramService
	@defs: {}

	@tags: (tag, callback) ->
		instance = new @ tag, callback or ->

	constructor: (@tag, @callback) ->
		@lastID = 0

	request: =>
		if def = @constructor.defs[@_url = @url()]
			return def.promise

		@lastDef = Blogvio.Aye.defer()
		@lastReq = $.getJSON(@_url, @lastDef.resolve).catch @onError
		@lastPromise = @lastDef.promise

	url: ->
		base = Router.url 'blogvio_instagram_proxy', {@tag}
		if @lastID then "#{base}?max_tag_id=#{@lastID}" else base

	# TODO
	cancel: =>
		# @lastDef.reject()
		# @lastReq.abort()
		@

	next: ->
		return unless @lastID?
		(@_queue or= Blogvio.Queue).defer (next) =>
			@request().then(onResponse.bind @).then(=> next())
				.fail @onError
		@

	onError: ->
		console.error 'InstagramService', arguments

module.exports = InstagramService
