#
# $Source: /home/blais/repos/cvsroot/arubomu/lib/python/arubomu/rip.py,v $
# $Id: rip.py,v 1.4 2005/03/01 05:17:04 blais Exp $
#

"""Data structures and parser for arubomu 'rip' and 'riplist' formats.

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.4 $"
__author__ = "Martin Blais <blais@furius.ca>"


from elementtree import ElementTree

from arubomu.album import Album
from arubomu.user import User
from arubomu.common import SimpleAttr



def load(f, read_album=False):
    """
    Reads an XML file and parses as an rip or riplist file.
    """

    tree = ElementTree.parse(f)
    root = tree.getroot()
    l = None
    if root.tag == 'rip':
        l = Rip().fromxml(root)
    elif read_album:
        if root.tag == 'album':
            l = Rip()
            alb = Album().fromxml(root)
            l.album = alb
    return l


def load_list(f):
    """
    Reads an XML file and parses as an rip or riplist file.
    """

    tree = ElementTree.parse(f)
    root = tree.getroot()
    l = None
    if root.tag == 'rip-list':
        l = []
        for c in root.getchildren():
            if c.tag == 'rip':
                l.append(Rip().fromxml(c))
##             elif c.tag == 'album' or c.tag == 'album-loose':
##                 r = Rip()
##                 r.album = Album().fromxml(c)
##                 l.append(r)
    return l



class Rip(SimpleAttr):

    """Class that represents a rip."""

    attribs = ['id']

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

        self.user = None
        self.album = None

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

        return cmp(x.id, y.id)

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

    def get_discs(self):

        """Returns a list of the available disc integers, taking into account
        the missing and extras."""

        if not self.album:
            return []

        nos = self.album.discs.keys()
        if self.user is not None:
            for disc in self.user.missing_discs:
                nos.remove(disc.no)
            for disc in self.user.extra_discs:
                nos.append(disc.no)
        return nos

    def fromxml(self, xel):

        assert xel.tag == 'rip'

        SimpleAttr.fromxml(self, xel, self.attribs, [])

        el = xel.find('user')
        if el != None:
            self.user = User().fromxml(el)

        el = xel.find('album')
        if el != None:
            self.album = Album().fromxml(el)

        return self

    def toxml(self):
        xel = ElementTree.Element('rip')

        SimpleAttr.toxml(self, xel, self.attribs, [])

        if self.user:
            xel.append(self.user.toxml())

        if self.album:
            xel.append(self.album.toxml())

        return xel
