#!/usr/bin/env python
# -*- coding: utf-8 -*-

import codecs
import os
import soundcloud

APIKEY = '6b54e93c3f6d3cb26253121b75c5af98'
LIMIT = 200
USER = '160231423'
OUT_PATH = os.path.expanduser('~/Music/webradio/soundcloud-favorites.pls')

client = soundcloud.Client(client_id=APIKEY)

print 'Collecting favorites'
next_href = 'users/{}/favorites'.format(USER)
favorites = []
while next_href:
    print 'Finding next {} elements'.format(LIMIT)
    result = client.get(next_href,
                        limit=LIMIT,
                        linked_partitioning=1)

    favorites.extend(result.collection)
    try:
        next_href = result.next_href
    except AttributeError:
        next_href = ''
        print 'Finished loading tracks.'

with codecs.open(OUT_PATH, 'w', 'utf-8') as outfile:
    print 'Creating playlist'
    outfile.write('[playlist]\n')

    for i, track in enumerate(favorites):
        artist = track.user.get('username')
        if not artist:
            artist = ''
        outfile.write(u'Title{}={} - {}\n'.format(i+1, artist, track.title))
        outfile.write(u'File{}={}?client_id={}\n'.format(
            i+1, track.stream_url, APIKEY))

    outfile.write('NumberOfEntries={}'.format(len(favorites)))

print 'Playlist created.'
print 'Number of tracks found: {}'.format(len(favorites))
