
Service = require '../../../browser/model'
Entry   = require '../../../browser/model/entry'
faqLink         = "<a class=\"add-content-instr-link\" target=\"_blank\" href=\"http://blog.widgetic.com/post/101481120261/how-to-load-your-content-from-dropbox\">How to load your content?</a>"

class DropboxPopupDriver extends Dropbox.Drivers.Popup
	openWindow: (url) -> @popup.location.href = url
	openPopup: -> @popup = 
		window.open '/connect/dropbox.html', '_dropboxOauthSigninWindow', @popupWindowSpec 980, 700

settings =
	client:
		key: 'ekn9VjZx0VA=|nnWESTkqe31UYqt/Qllbpa2sjX1YmmcmNEPH/vwn0w=='
		sandbox: true
		fileRoot: 'auto'
	driver:
		receiverUrl  : "https://widgetic.com/connect/dropbox"
		rememberUser : true

Mime  =
	image:['image/png','image/jpeg','image/jpg','image/gif','image/bmp']
	audio:['audio/mp3','audio/mpeg']
	video:['video/mp4']
	folder:['inode/directory']

Dropbox.Stat.prototype.entry = (service,entry)->
	props = { @name, @path,id:@path}
	props.type = k for k,v of Mime when v.indexOf(@mimeType) > -1
	new Entry(props)

class DropboxService extends Service
	responses: {}
	faqLink: $ faqLink

	constructor: ->
		super
		@authenticated = false
		(@client = new Dropbox.Client settings.client).authDriver new DropboxPopupDriver settings.driver
		@allMime = [].concat.apply([], (Mime[type] for type in @options.types when Mime[type]?)).concat Mime.folder
		# 
		@root.navTitle = 'Dropbox/Apps/Blogvio'

	_auth: (interactive=true) ->
		DropboxPopupDriver::openPopup() if interactive
		@client.authenticate {interactive}, @onAuth

	onAuth:(error,client)=>
		@trigger 'auth', not error and client.isAuthenticated()
		@client.reset() if error

	refresh:(entry)->		
		@client.stat entry.path, {readDir: true, cacheHash: entry.hash}, (e, stat, entries) =>

			entry.hash = stat?.versionTag or entry.hash
			if e and e.status = 304
				entries = @responses[entry.hash] or []
			else
				entries = entries.filter((i)=>@allMime.indexOf(i.mimeType)>-1).map (i)->i.entry()
				@responses[entry.hash] = entries
			@trigger 'refresh', entries
			
	getURL:(entry,callback)->
		if entry.url
			return callback(entry.url)
		@client.makeUrl entry.path, {downloadHack:true,long:true},(error,purl)->
			callback(purl.url)

	preview:(entry)->@client.thumbnailUrl entry.path,size:'m'
	deauth:->@client.signOut =>@trigger 'auth',false

module.exports = DropboxService