#!/usr/bin/python

import sys
import os
import time
import getopt
import locale

import lastfm
import lastfm.marshaller

USAGE = """\
usage: lastfmsubmitd [--encoding ENC] [--artist ARTIST] [--title TITLE]
    [--length LEN] [--time STAMP] [--album ALBUM] [--mbid TRACKID]
    [--encoding ENC] [--stdout] [--debug] [--quiet] [--help]"""

if __name__ == '__main__':
    shortopts = 'e:a:s:l:d:b:m:sdqh'
    longopts = [
        'encoding=',
        'artist=',
        'title=',
        'length=',
        'time=',
        'album=',
        'mbid=',
        'stdout',
        'debug',
        'quiet',
        'help',
        ]

    try:
        opts, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
    except getopt.GetoptError, e:
        print >>sys.stderr, 'lastfmsubmit: %s' % e
        print >>sys.stderr, USAGE
        sys.exit(1)

    sub = {}
    encoding = locale.getpreferredencoding()
    stdout = False
    debug = False
    stderr = True

    for opt, arg in opts:
        if opt in ('--encoding', '-e'):
            encoding = arg
        if opt in ('--debug', '-d'):
            debug = True
        if opt in ('--quiet', '-q'):
            stderr = False

    try:
        log = lastfm.logger('lastfmsubmit', debug=debug, stderr=stderr)
    except IOError, e:
        print >>sys.stderr, 'lastfmsubmit: error opening log: %s' % e
        sys.exit(1)

    try:
        for opt, arg in opts:
            try:
                if opt in ('--artist', '-a'):
                    sub['artist'] = lastfm.marshaller.guess_enc(arg, encoding)
                elif opt in ('--title', '-t'):
                    sub['title'] = lastfm.marshaller.guess_enc(arg, encoding)
                elif opt in ('--length', '-l'):
                    sub['length'] = lastfm.marshaller.parse_length(arg)
                elif opt in ('--time', '-i'):
                    sub['time'] = time.strptime(arg, lastfm.TIME_FMT)
                elif opt in ('--album', '-b'):
                    sub['album'] = lastfm.marshaller.guess_enc(arg, encoding)
                elif opt in ('--mbid', '-m'):
                    sub['mbid'] = arg
                elif opt in ('--stdout', '-s'):
                    stdout = True
                elif opt in ('--help', '-h'):
                    print USAGE
                    sys.exit(0)
            except ValueError:
                print >>sys.stderr, "lastfmsubmit: can't parse %s" % opt
                sys.exit(1)

        if len(sub) == 0:
            print >>sys.stderr, "lastfmsubmit: nothing specified"
            print >>sys.stderr, USAGE
            sys.exit(1)
        if not sub.has_key('time'):
            sub['time'] = time.gmtime()

        if stdout:
            print lastfm.marshaller.dump(sub)
        else:
            try:
                log.debug('Sending %s to daemon' % lastfm.repr(sub))
                lastfm.submit([sub])
            except IOError:
                log.error("Can't write sub: %s" % e)
                sys.exit(1)

    except SystemExit, e:
        sys.exit(e.args[0])
    except:
        import traceback
        einfo = traceback.format_exception(*sys.exc_info())
        log.error('Aborting: %s' % ''.join(einfo))
        sys.exit(1)
