#!/usr/bin/env python
# Copyright (c) 2002 Nathan Sharfi
# Copyright terms are included in a file called 'license.txt'.
import os, sys, fnmatch
import flac, files
from options import options as o

class IWavMaker:
    """I define the interface for getting .wav files."""
    def __init__(self, wavDir=None):
        self.wavDir = wavDir or o.wavDir
        
    def getFilenames(self):
        "I return the names of the .wav files in the wav directory."
        try:
            l = os.listdir(self())
        except OSError: # can't assume that I'm getting an errno of 2
            # logic? -> # so I'll assume that it's a (dir not found) error
            print "Error: WAV file dir (%s) does not exist." % (self())
            print "(Did you run sonice in the right directory?)"
            sys.exit(1)
            
        l.sort()
        l =  map(_prependPath, l)
        return l
    
    def __call__(self):
        """Implement me in derived classes to override how the dir property
        gets calculated."""
        
        raise NotImplementedError

class Preexisting(IWavMaker):
    def __init__(self, wavDir=None):
        """Typical initializer.
        dir is the name of the directory where the .wav files are."""
        IWavMaker.__init__(self, wavDir)
        _checkWavDir(self.wavDir)
        
        print "using preexisting wavs..."

    def __call__(self):
        return self.wavDir
    
class FlacDecoding(IWavMaker):
    def __init__(self, wavDir=None, flacDir=None):
        IWavMaker.__init__(self, wavDir)

        self.flacDir = flacDir or o.flacDir
        self.wavDir = wavDir or o.wavDir
        self.made = False
        
        _checkWavDir(self.wavDir)
        if not os.path.isdir(self.flacDir):
            raise files.InvalidDirectoryError, self.flacDir
        print "using flacs..."
        
    def __call__(self):
        if not self.made:
            flac.BatchDecompressor(self.flacDir, self.wavDir, o.quiet)()
            self.made = True

        # okay, it's ready!
        return self.wavDir

class Cdparanoia(IWavMaker):
    """Creates wavs by ripping a CD and placing the extracted files XXX."""
    def __init__(self, wavDir=None, device=None):
        IWavMaker.__init__(self)
        self.wavDir = wavDir or o.wavDir
        _checkWavDir(wavDir)
        raise NotImplementedError

    def __call__(self):
        raise NotImplementedError
    
###############################################################################
def _prependPath(f):
    """Prepends the 'normal' path to a wav file"""
    return os.path.join(o.wavDir, f)

def _checkWavDir(wavDir):
    """Checks to see if wavDir exists, and if not, tries to create it."""
    if not os.path.isdir(wavDir): 
        if os.path.isfile(wavDir):  # XXX: fails if wavDir is a symlink?
            raise InvalidDirectoryError, wavDir
        os.makedirs(wavDir)

def _checkFilesInWavDir(wavDir):
    _checkWavDir(wavDir)
    l = os.path.listdir(wavDir)
    if fnmatch.filter("*.wav", l) == []:
        print "no .wav files in %s, exiting..."  % (wavDir)
        sys.exit(1)

if __name__ == "__main__":
    p = Preexisting("blahblah")
    fd = FlacDecoding('/home/comatoast/rips', '/')
    print fd()
