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

# SoundCloud config
widgetic_backend_url = 'https://widgetic.com/wservices/soundcloud/'
SC = require('soundcloud')
config = {
	api_url: 'https://api.soundcloud.com'
	# for '/connect' endpoint
	client_id :  'aed0aa63baf747a83ad0b6b246acddca'
	# client_secret: '3173e3098379153d42084aba06fe3ec4',
	redirect_uri: 'https://widgetic.com/connect/soundcloud',
	tracks_url:   widgetic_backend_url + 'tracks/',
	# response_type: 'code',

	# for '/oauth2/token' endpoint
	grant_type: 'refresh_token',
}
SC.initialize(config);

# add local config options used in this file only
SC.client_id = config.client_id
SC.api_url = config.api_url
SC.tracks_url = config.tracks_url
try SC.auth_token = localStorage.getItem 'soundcloudAuthToken'
try SC.userId = localStorage.getItem 'soundcloudUserId'

class SoundCloudService extends Service
	constructor: ->
		super
		# console.log('Soundcloud Service CTR:', @title, @options)
	
	SCGet: (path) ->
		url = "#{SC.api_url}" + path
		# console.log("SCGet path:", path, SC.auth_token)
		$.ajax(url: url, type: 'GET', dataType: 'json', headers: {'Authorization': 'OAuth ' + SC.auth_token})

	auth: (interactive) => 
		# console.log("SoundCloud on auth:", SC.auth_token, SC.userId);

		# show popup to authenticate
		if !SC.userId and interactive then @showAuthPopup()

		# trigger auth event to show folders or connect button in browser
		else @checkAuth()

	showAuthPopup: ->
		# console.log("SC showAuthPopup:", SC)
		SC.connect()
			.then((response) =>
				# console.log("SC did connect:", response);
				# get auth_token
				SC.auth_token = response.oauth_token
				try localStorage.setItem 'soundcloudAuthToken', SC.auth_token
				# console.log("SC did connect:", SC);

				# get user info
				@SCGet("/me")
					.then((response) => 
						# console.log("SC getUser result:", response)
						SC.userId = response.id
						try localStorage.setItem 'soundcloudUserId', SC.userId
						@checkAuth();
					).catch (error) => 
						console.log("Editor getUser error:", error)
						@deauth()
			).catch (error) =>
				console.log 'SC Connect Error: ' + error.message
				@deauth()

	checkAuth: =>
		# console.log 'checkAuth:', SC.userId
		@trigger 'auth', SC.userId != null

	deauth: ->
		# remove auth_token
		SC.auth_token = null
		try localStorage.removeItem 'soundcloudAuthToken'

		# remove user
		SC.userId = null
		try localStorage.removeItem 'soundcloudUserId'

		# trigger auth event
		@checkAuth();

	# SoundCloud Files explorer methods
	refresh: (@currentFolder) ->
		# console.log("Soundcloud service refresh:", @currentFolder)
		# if root folder: load subfolders(playlists) and then files
		if @currentFolder.root then @fetchPlaylists()

		# if subfolder: load files(tracks) inside
		else @fetchTracks @currentFolder.id

	fetchPlaylists: =>
		# console.log("fetchPlaylists!");
		@SCGet("/users/#{SC.userId}/playlists")
				.then((playlists) => 
					# console.log("fetchPlaylists result:", playlists);

					# trigger refresh event to show in browser the playlists folders
					@trigger 'refresh', (playlists.map @newEntry.bind @, 'folder'), {root: true}

					# load tracks of root folder
					@fetchTracks @currentFolder.id
				).catch (error) => 
					console.log 'Fetch Playlist error: ' + error.message

	fetchTracks: (playlistId) =>
		# console.log("fetchTracks for playlist:", playlistId)
		# check if a playlist or entire list of tracks of the current user
		path = if playlistId then "/playlists/#{playlistId}" else "/users/#{SC.userId}/tracks"
		path += "?access=playable"
		

		@SCGet(path)
				.then((result) =>
					# console.log("fetchTracks result:", result)

					# if root then read directly the tracks
					tracks = result

					# if a playlist then get the tracks inside
					if result.tracks then tracks = result.tracks

					# trigger event to refresh in browser
					@trigger 'refresh', (tracks.map((track) => @newEntry('audio', track))), {root: (if playlistId then false else true)}
				).catch (error) => 
					console.log 'Fetch Tracks error: ' + error.message

	newEntry: (type, item, parentId) =>
		# console.log("newEntry:", type, item, parentId)
		if !parentId
			path = @currentFolder.path
			path += '/' unless @currentFolder.root
		else path = parentId + '/'
		path += item.id
		# console.log("newEntry:", path, item.id, type)
		if type == "folder" then children = item.tracks
		{artwork_url, id, duration, title, stream_url} = item
		new Entry $.extend {}, {
			service: @
			type, path, artwork_url, id, children, duration: duration/1000, title, stream_url
			name: item.title
		}

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

		# new 2021 api track path through widgetic endpoint
		callback "#{SC.tracks_url}?id=#{entry.id}&atoken=#{SC.auth_token}"
		
		# new 2021 api get method
		# @SCGet("/tracks/#{entry.id}/streams")
		# 		.done((streams) => 
		# 			console.log("fetchTrackStreams result:", streams);
		# 			# callback streams.http_mp3_128_url
		# 		).fail (error) => 
		# 			console.log 'Fetch Track Streams error: ' + error

module.exports = SoundCloudService
