#!/usr/bin/env python
#
# $Source: /home/blais/repos/cvsroot/arubomu/bin/arubomu-convert,v $
# $Id: arubomu-convert,v 1.19 2004/03/03 18:38:10 blais Exp $
#

"""arubomu-convert [<options>] <cattype:catnumber> [<cattype:catnumber> ...]

Online album catalog fetcher and parser.

This is mainly a front-end to the library that implements this.
Give it a set of catalog numbers to fetch, pre-pended in the following fashion::

   <catalog-type>:<catalog-number>

e.g.::

   amazon:B0000549UU descarga:TL-20351.10 ...

"""

__author__ = "Martin Blais <blais@furius.ca>"
__version__ = "$Id: arubomu-convert,v 1.19 2004/03/03 18:38:10 blais Exp $"


import sys, os
import re

from elementtree.ElementTree import ElementTree
from elementtree_pretty import write_pretty

from arubomu import album, rip, user
from arubomu.parsers import getfetcher



xmlindent = os.environ.get('XMLLINT_INDENT', '   ')


def main():
    import optparse
    parser = optparse.OptionParser(__doc__)
    parser.add_option('-s', '--store-files', action='store_true',
                      help="Automatically guess appropriate filenames and "
                      "store the data in files in the current directory")
    parser.add_option('-o', '--output', action="store",
                      help='Store all outputs in the given filename')
    parser.add_option('-r', '--rip', action='store_true',
                      help="Enclose album in a rip with empty fields.")
    opts, args = parser.parse_args()

    if not args:
        raise parser.error('you need to specify catalog numbers.')

    if opts.output and opts.store_files:
        raise SystemExit("Error: cannot both output ot file and store.")

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

    # parse catalog entry specs.
    pairs = []
    argre = re.compile('([^:]+):(.+)')
    urlre = re.compile('(http|ftp|file):(.+)')
    for arg in args:
        mo = argre.match(arg)
        if not mo:
            raise parser.error("invalid catalog spec format '%s'" % arg)
        cattype, rest = mo.groups()
        mo = urlre.match(rest)
        if mo:
            pairs.append( (cattype, None, rest) )
        else:
            pairs.append( (cattype, rest, None) )

    # for each entry requested, get appropriate fetcher and parse url contents.
    for cattype, catnum, url in pairs:
        fetcher = getfetcher(cattype)
        if not url:
            url = fetcher.geturl(catnum)

        print >> sys.stderr, '===== Processing:', url
        alb, images = fetcher.fetch(url)

        if not alb:
            print >> sys.stderr, \
                  'Error: Could not parse album. Maybe', \
                  'the catalog number is incorrect?'
            continue

        if images:
            for coverfn in images:
                print >> sys.stderr, '===== Cover image:', coverfn

        if opts.store_files:
            try:
                sffn = '%s.xml' % album.guess_id(alb)
                print >> sys.stderr, '===== Storing in file:', sffn
                outf = open(sffn, 'w')
            except IOError, e:
                raise SystemExit("Error: cannot open output file (%s)" % str(e))
                
        if opts.rip:
            r = rip.Rip()
            r.album, r.user = alb, user.User()
            r.user.init_basic_empty()
            alb = r

        tree = ElementTree(alb.toxml())
        write_pretty(tree, outf, encoding='ISO-8859-1', indent=xmlindent)
        print

# Run main if loaded as a script
if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print >> sys.stderr, '\nInterrupted.'
