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

app_key = 'e80667fd637788dde877f5684d496d85'
localStorage.removeItem 'flickrAuthToken' if localStorage.getItem('flickrTokenFor') isnt app_key
localStorage.setItem 'flickrTokenFor', app_key

api =
	key: app_key
	secret: '5a90030ecac5b4fc'
   # sig: MD5(secret+'api_key'+[api_key]+'perms'+[perms])
	sig: '05eb1494ce939ce3098bbcdc7300b5e3'
	token: localStorage.getItem('flickrAuthToken')?.split('::')[0]
	nsid: localStorage.getItem('flickrAuthToken')?.split('::')[1]
	perms: "read"
	rest: 'https://api.flickr.com/services/rest/'

class FlickrService extends Service
	auth_url: "https://flickr.com/services/auth/?api_key=#{api.key}&perms=#{api.perms}&api_sig=#{api.sig}"
	constructor: ->
		super
		@authenticated = (api.token? and api.nsid?)
		@options.types.push 'photo' if 'image' in @options.types

	refresh: (@entry) =>
		@getMediaList().done @_onRespond

	_auth: (interactive = true) ->
		@trigger 'auth', @authenticated
		(!@authenticated and interactive) and @doAuth()

	doAuth: =>
		window.flickrReady = (frob) =>
			@call({api_key: api.key, frob, method: 'flickr.auth.getToken'}).done (resp) =>
				resp        = $(resp)
				api.nsid    = resp.find('user').attr('nsid')
				api.token   = resp.find('token').text()
				localStorage.setItem 'flickrAuthToken', api.token+'::'+api.nsid

				@trigger 'auth', @authenticated = true

		window.open @auth_url, 'Flickr connect', 'width=990,height=825' unless api.token?

	deauth:->
		@trigger 'auth', @authenticated = false
		localStorage.removeItem('flickrAuthToken')

	getMediaList: -> @call
		api_key: api.key, auth_token: api.token, extras: 'media',
		format: 'json', method: 'flickr.people.getPhotos', nojsoncallback: 1
		user_id: api.nsid

	listEntries: (data) =>
		for media in data when media.media in @options.types
			media.type = @options.types[0]
			media.path = '/'+media.id
			new Entry media

	_onRespond: (data) =>
		return @trigger 'refresh', @entry.children = [] unless data.photos.total

		@trigger 'refresh', @entry.children = @listEntries data.photos.photo

	call: (params={},callback) =>
		params['api_sig'] = api.secret + ("#{key}#{value}" for key,value of params).join('')
		params['api_sig'] = Crypto.MD5 params['api_sig']
		$.ajax api.rest, data:params

	preview: (entry) ->
		"https://farm#{entry.farm}.staticflickr.com/#{entry.server}/#{entry.id}_#{entry.secret}_q.jpg"

	getURL: (entry, callback) ->
		if entry.type is 'image'
			callback "https://farm#{entry.farm}.staticflickr.com/#{entry.server}/#{entry.id}_#{entry.secret}.jpg"
		else @getVideoSizes(entry).done (data) => @videoUrl data.sizes.size, callback

	getVideoSizes: (entry) -> @call
		api_key: api.key, auth_token: api.token,
		format: 'json', method: 'flickr.photos.getSizes', nojsoncallback: 1
		photo_id: entry.id, user_id: api.nsid

	videoUrl: (sizes, callback) ->
		return callback size.source for size in sizes when size.label is 'Site MP4'

module.exports = FlickrService
