#
# $Source: /home/blais/repos/cvsroot/arubomu/lib/python/arubomu/cdindex.py,v $
# $Id: cdindex.py,v 1.29 2004/02/15 23:14:36 blais Exp $
#

"""Parser for CD index file.

The CD index file format is just a convenient file format that is edited by hand
to store a list of short information about albums in single files. It is just a
convenience, and it is incomplete in comparison to the arubomu XML formats,
i.e. it cannot contain all the information that is stored in arubomu.  The
author is using this format to take down quick notes of wanted albums and future
albums to purchase.

The format is simple, here is an example::

  - keyword, artist, title, label, release-date

    Arbitrary description text and reviews (indented).

The components can be quoted with double-quotes. The label and release date are
optional.  Text prefixed by # is ignored as comments.
"""

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


import sys
import re

from elementtree.ElementTree import ElementTree, Element

from arubomu.album import Album

import enjot


idxe = re.compile('^[-=&/\?O] (.+)$')
attrre = re.compile('^  (.+)$')
atere = re.compile('^(.+)="(.*)"$')
tlre = re.compile('^TL-(\d+).(\d+)$')
pagre = re.compile('^\014')
wsre = re.compile('^\s*$')


fieldesc = ['keyword', 'artist', 'title', 'label', 'reldate']


def load(f, encoding='iso-8859-1'):

    """Load and parse the given file as a cdindex file."""

    entries = enjot.load(f)

    alist = []
    for fields, text in entries:

        a = Album()
        alist.append(a)

        for val, name in zip(fields, fieldesc):
            setattr(a, name, unicode(val, encoding))

        if text != None:
            a.reviews.append( unicode(text, encoding) )
    return alist
    

def save(alist, f, encoding='iso-8859-1'):

    """Save a list of albums as a cdindex file."""

    entries = []
    for a in alist:
        fields = []
        for fld in fieldesc:
            v = getattr(a, fld, None)
            vv = v and v.encode(encoding) or None
            fields.append(vv)
        text = None
        if a.reviews:
            text = a.reviews[0].encode(encoding)
        entries.append( (fields, text) )
        
    enjot.save(f, entries)



def main():
    import optparse
    parser = optparse.OptionParser(__doc__.strip(), version=__version__)
    global opts
    opts, args = parser.parse_args()

    if 0:
        xel = Element('album-list')
        for fn in args:
            albums = load(open(fn, 'r'))
            for a in albums:
                xel.append(a.toxml(loose=True))
    
        tree = ElementTree(xel)
        from elementtree_pretty import write_pretty
        write_pretty(tree, sys.stdout, encoding='iso-8859-1', indent='   ')
        print
    else:
        for fn in args:
            albums = load(open(fn, 'r'))
            save(albums, sys.stdout, 'iso-8859-1')

# Run main if loaded as a script
if __name__ == "__main__":
    main()
