#
# $Source: /home/blais/repos/cvsroot/arubomu/lib/python/arubomu/songlist.py,v $
# $Id: songlist.py,v 1.3 2004/04/03 22:00:32 blais Exp $
#

"""Data structures and parser for arubomu 'songlist' format.

This modules provides some format independent data structures and conversion
from/to XML, and implements some assumptions in the data structures conversion.

"""

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


import sys, os
import re

from elementtree import ElementTree

from arubomu.common import SimpleAttr



def load(f):
    """Reads an XML file and parses as a songlist file."""

    tree = ElementTree.parse(f)
    root = tree.getroot()
    if root.tag == 'songlists':
        els = root.getchildren()
    elif root.tag == 'songlist':
        els = [root]
    else:
        raise StandardError("Root element is not a songlist.")

    songlists = []
    for el in els:
        sl = Songlist().fromxml(el)
        songlists.append(sl)
    return songlists



class Songlist(SimpleAttr):

    """Class that represents an album."""

    attribs = ['name']

    elems = ['comments']

    def __init__(self):
        SimpleAttr.__init__(self, self.attribs + self.elems)

        # list of Song instances
        self.songs = []

    def __cmp__(x, y):
        "Sort according to artist, then release date, then title."

        return cmp(x.name, y.name)

    def __repr__(self):
        r = SimpleAttr.__repr__(self, self.attribs + self.elems)
        for s in self.songs:
            r += repr(s)
        return r

    def fromxml(self, xel):

        assert xel.tag == 'songlist'

        SimpleAttr.fromxml(self, xel, self.attribs, self.elems)

        self.songs = []
        for cel in xel.getchildren():
            if cel.tag == 'songref':
                s = Songref().fromxml(cel)
                self.songs.append(s)
        return self
        
    def toxml(self):
        xel = ElementTree.Element('songlist')

        SimpleAttr.toxml(self, xel, self.attribs, self.elems)

        for s in self.songs:
            xel.append( s.toxml() )

        return xel


class Songref(SimpleAttr):

    attribs = ['dir', 'no', 'note', 'begin', 'end',
               'stretch', 'gain', 'rating', 'comment']

    def __init__(self):
        SimpleAttr.__init__(self, self.attribs)

    def __repr__(self):
        return SimpleAttr.__repr__(self, self.attribs)

    def fromxml(self, xel):
        assert xel.tag == 'songref'
        SimpleAttr.fromxml(self, xel, self.attribs, [])
        if self.no: self.no = int(self.no)
        return self

    def toxml(self):
        xel = ElementTree.Element('songref')
        SimpleAttr.toxml(self, xel, self.attribs, [])
        return xel
