#!/usr/bin/python

import datetime
import getpass
from optparse import OptionParser
import subprocess
import sys

import mutagen
from mutagen import easyid3

from gobble import get_parser, GobbleServer, GobbleTrack


def _parse_date(string):
    process = subprocess.Popen(['date', '-d %s' % (string,), '+%s'],
                               stdout=subprocess.PIPE)
    string = process.communicate()[0].strip()
    return datetime.datetime.utcfromtimestamp(float(string))


if __name__ == '__main__':
    usage = "%prog [--server <SERVER>] <USERNAME> <START TIME> <MEDIA FILES>"
    parser = get_parser(usage=usage)
    opts,args = parser.parse_args()
    if len(args) < 3:
        parser.error("All arguments are required.")

    username,start_string = args[:2]
    server = opts.server
    password = getpass.getpass()
    tracks = args[2:]
    server = GobbleServer(server, username, password)

    dt = _parse_date(start_string)
    input = ''
    while input not in ['y', 'n']:
        input = raw_input("Did you mean '%s UTC'? [Y/n]: " % (dt,)).lower()
    if input == 'n':
        sys.exit()

    for track in tracks:
        f = mutagen.File(track)
        if f is None:
            raise Exception("%s caused problems." % (track,))
        if isinstance(f, mutagen.mp3.MP3):
            f = mutagen.mp3.MP3(track, ID3=easyid3.EasyID3)
        title = f['title'][0]
        artist = f['artist'][0]
        length = f.info.length
        album = f['album'][0]
        tracknumber = f['tracknumber'][0]
        t = GobbleTrack(artist, title, dt, album=album, length=length,
                        tracknumber=tracknumber)
        server.add_track(t)
        dt += datetime.timedelta(seconds=length)
    server.submit()

@@ -618,60 +618,540 @@
     
-opts,args = parser.parse_args()%0A    if len(args) %3C 3
+parser.add_option('-j', '--just-finished', action=%22store_true%22,%0A                      help=%22Works out START TIME as if you've just finished%22%0A                           %22 listening to MEDIA FILES.  START TIME argument%22%0A                           %22 will be treated as a media file, so don't pass%22%0A                           %22 it.%22)%0A    parser.set_defaults(just_finished=False)%0A    opts,args = parser.parse_args()%0A    if opts.just_finished:%0A        expected_args = 2%0A    else:%0A        expected_args = 3%0A    if len(args) %3C expected_args
 :%0A  
@@ -1213,17 +1213,70 @@
 username
-,
+ = args.pop(0)%0A    if not opts.just_finished:%0A        
 start_st
@@ -1290,12 +1290,15 @@
 args
-%5B:2%5D
+.pop(0)
 %0A   
@@ -1373,12 +1373,8 @@
 args
-%5B2:%5D
 %0A   

Set up parsing of --just-finished argument to offline-submit.py.