Service = require '../../../browser/model'
Entry   = require '../../../browser/model/entry'
SC      = require '../../../core/services/soundcloud'

class SoundCloudService extends Service
	constructor: ->
		super
		@authenticated = false

	auth: (interactive) => SC.ready().then =>
		SC.connect @checkAuth if interactive
		@checkAuth()

	checkAuth: =>
		@trigger 'auth', @authenticated = SC.isConnected()

	refresh: (@currentFolder) ->
		@fetchPlaylists() if @currentFolder.root
		@fetchTracks @currentFolder.id

	fetchPlaylists: =>
		SC.get '/me/playlists', (playlists) =>
			@trigger 'refresh', playlists.map @newEntry.bind @, 'folder'

	fetchTracks: (id) =>
		path = if id then "/playlists/#{id}" else '/me'

		SC.get path+'/tracks', (tracks) =>
			@trigger 'refresh', tracks.map @newEntry.bind @, 'audio'

	newEntry: (type, item) =>
		path = @currentFolder.path
		path += '/' unless @currentFolder.root
		path += item.id
		{artwork_url, id, duration, title, stream_url} = item
		new Entry $.extend {}, {
			service: @
			type, path, artwork_url, id, duration, title, stream_url
			name: item.title
		}

	getURL: (entry, callback) ->
		callback "#{entry.stream_url}?client_id=#{SC.clientId()}"

	deauth: ->
		SC.disconnect()
		@trigger 'auth', @authenticated = SC.isConnected()

module.exports = SoundCloudService
