#!/usr/bin/env python
#
# $Source: /home/blais/repos/cvsroot/arubomu/bin/arubomu-convert-id3,v $
# $Id: arubomu-convert-id3,v 1.13 2005/02/07 23:10:39 blais Exp $
#

"""arubomu-id3-to-xml [<options>] <file> [<file> ...]

Reads the MP3 files in the given directory and converts the ID3 tag info to XML.
We group the tags according to similar (artist, album-title) pairs.

This is used to create a decent skeleton XML file (to be edited) from the
information in the id3 tags in the file.
"""

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


import sys

from arubomu.album import Album, Disc, Song
from arubomu import id3tags

from elementtree.ElementTree import ElementTree
from elementtree_pretty import write_pretty


def main():
    import optparse
    parser = optparse.OptionParser(__doc__)
    parser.add_option('-o', '--output', action="store",
                      help="Output filename")
    parser.add_option('-v', '--compilation', '--various-artists',
                      action='store_true',
                      help="Assume songs are from a compilation.")
    opts, args = parser.parse_args()

    if not args:
        raise parser.error("you need to specify some mp3 files.")
    files = args

    albums = {}
    if opts.compilation:
        a = Album()
        a.title = '(Unknown Compilation)'
        a.artist = 'Various Artists'
        a.discs[1] = Disc(1)
        albums[None] = a

    for fn in files:
        tags = id3tags.ID3Tags(fn)
        if opts.compilation:
            a = albums[None]
        else:
            title, artist = tags.album, tags.artist
            id = (title, artist)
            try:
                a = albums[id]
            except KeyError:
                a = Album()
                albums[id] = a

            a.title, a.artist = id
            a.reldate = tags.year

        try:
            d = a.discs[1]
        except KeyError:
            d = Disc(1)
            a.discs[1] = d

        no = tags.track or (max(d.songs.keys() + [-1]) + 1)
        s = Song(int(no))
        d.songs[int(no)] = s
        s.title = tags.title
        if opts.compilation:
            s.artist, s.album = tags.artist, tags.album

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

    for a in albums.values():
        xel = a.toxml()

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


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