#!/usr/bin/env python
#
# $Source: /home/blais/repos/cvsroot/arubomu/bin/arubomu-convert-filenames,v $
# $Id: arubomu-convert-filenames,v 1.16 2005/03/01 17:13:52 blais Exp $
#

"""arubomu-filenames-to-xml [<options>] <file> [<file>]

Reads the MP3 files in the given directory and converts the filenames into an
XML file with song titles.  It cannot guess anything else from the album.

This can be used to create the skeleton XML file for the songs and then you fill
up the missing parts.

"""

__version__ = "$Revision: 1.16 $"
__author__ = "Martin Blais <blais@furius.ca>"


import sys, re

from elementtree.ElementTree import ElementTree
from elementtree_pretty import write_pretty

from arubomu.album import Album, Disc, Song


mp3re_very_loose = re.compile('^(.*)\.(mp3|ogg|wma)$')
mp3re_loose = re.compile('^(\d\d\d?)(.*)\.(mp3|ogg|wma)$')
    

def cleanname(n):
    if n is None: return n
    
    n = n.decode('latin-1')
    n = n.strip()
    if n.startswith('-'):
        n = n[1:]
    if n.endswith('-'):
        n = n[:-1]
    n = n.strip()
    return n


def main():
    import optparse
    parser = optparse.OptionParser(__doc__)

    parser.add_option('-o', '--output', action="store",
                      help="Output filename")
    parser.add_option('-s', '--separate-artist-title', action='store',
                      default=None,
                      help="Artist and Title are split with given separator")

    opts, args = parser.parse_args()

    if not args:
        raise SystemExit('Error: please specify a list of files')
    files = args

    a = Album()
    d = Disc(1)
    a.discs[1] = d
    n = -1
    for fn in files:
        s = Song()
        mo = mp3re_loose.match(fn)
        if mo:
            sno, name, ext = mo.groups()
            s.no = int(sno)
            s.title = name.strip()
            d.songs[s.no] = s
        else:
            mo = mp3re_very_loose.match(fn)
            if mo:
                s.no = n
                n -= 1
                s.title = mo.group(1).strip()
                d.songs[s.no] = s

        # split title if necessary
        if opts.separate_artist_title:
            otitle = re.split('(.*)%s(.*)' % opts.separate_artist_title, s.title)
            if len(otitle) > 1:
                s.artist = otitle[0].strip()
                s.title = s.title[len(otitle[0]):].strip()

        # clean up some of the title and artist
        s.title = cleanname(s.title)
        s.artist = cleanname(s.artist)

    if opts.output:
        of = open(opts.output, 'w')
    else:
        of = sys.stdout

    xel = a.toxml()
    tree = ElementTree(xel)
    write_pretty(tree, of, encoding='iso-8859-1')

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print "Interrupted, exiting."
