#!/usr/bin/env python
# Copyright (c) 2002 Nathan Sharfi
# Copyright terms are included in a file called 'license.txt'.
import os, sys
import traceback

import prioritymanager
from options import options as o
import wavmaker
import ogg
from vorbisinfo import VorbisInfoList
import vorbisgain
from prioritymanager import priorityManager

class IOggLayer:
    """I define the common interface for all objects that create ogg vorbis
    files from VorbisInfo objects."""

    def __init__(self): pass
    def lay(self):
        """Begins the process of generating the Ogg Vorbis files."""
        raise NotImplementedError, 'derive from me first'
        
class Serial(IOggLayer):
    def __init__(self, wavMaker, infoAdder, oggDir=None, priorityFunc=None):
        IOggLayer.__init__(self)
        self.wavMaker = wavMaker
        self.infoAdder = infoAdder
        self.oggDir = oggDir or o.oggDir
        self.priorityFunc = priorityFunc or priorityManager

    def lay(self):
        try:
            vil = VorbisInfoList(self.wavMaker, self.infoAdder)
        except ValueError, what:
            print what
            print '(bailing out in Serial.__call__())'
            sys.exit(1)          
        
        for vi in vil:
            compressor = ogg.Compressor(vi.inFile,
                               os.path.join(self.oggDir, vi.outFile),
                               o.quality, vi.comments)
            compressor.cmd = self.priorityFunc(compressor.cmd)
            compressor.compress()

        # find out if we should do vorbisgain
        doIt = lambda : vorbisgain.vorbisgainBunch(self.oggDir)
        if o.doVorbisgain:
            if 'vorbisgain' in vil.pragmas:
                if vil.pragmas['vorbisgain']:
                    doIt() # the pragma was there, and it said to do it
            else:
                doIt() # the pragma wasn't in the list, so do it by default
        else:
            pass # don't do it, the options didn't say to (they override)
        

class Parallel(IOggLayer):
    pass

class Piped(IOggLayer):
    """I create oggs by piping the output of flac to oggenc, skipping the
    .wav-creating step.
    I dunno if my architecture can handle this beautifully, but we might
    see yet."""
    pass
    
