#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2012, 2013 Naglis Jonaitis
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation

"""A script which helps you to listen to/download songs from leftasrain.com
from the comfort of your terminal."""

import argparse
import json
import queue
import threading
import urllib.request


NEXT_TRACK_URL = "http://leftasrain.com/getNextTrack.php?currTrackEntry={id:d}&shuffle={shuffle:s}"
# this can change over time
SONG_URI = "http://leftasrain.com/musica/%s.mp3"


def get_song_count():
    """Returns the total number of songs on leftasrain.com"""

    return int(get_song_data(0)[0])


def get_song_data(id):
    """Returns a list of song attributes"""

    result = urllib.request.urlopen(NEXT_TRACK_URL.format(id=id,
                                                          shuffle="false"))
    return json.loads(result.read().decode("utf-8"))


def worker():
    while True:
        id = queue.get()
        results[id] = SONG_URI % get_song_data(id)[4]
        queue.task_done()


queue = queue.Queue()
results = {}
if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-l", "--last", dest="last", metavar="N", type=int,
                        help="download last %(metavar)s songs", default=0)
    parser.add_argument("-t", "--threads", dest="threads", type=int,
                        default=2, metavar="THREADS",
                        help="number of execution THREADS")
    args = parser.parse_args()

    n = get_song_count() + 1
    for i in range(n, args.last == 0 and 1 or n - args.last, -1):
        queue.put(i)

    for i in range(args.threads):
        t = threading.Thread(target=worker)
        t.daemon = True
        t.start()

    # wait for all threads to finish
    queue.join()

    for id in sorted(results.keys(), reverse=True):
        print(results[id])
