#!/usr/bin/env python
# Copyright (c) 2002 Nathan Sharfi
# Copyright terms are included in a file called 'license.txt'.
"""I contain functions for manipulating flac-encoded music archives.
These are all implemented as callable objects so clients can access the command
to add extra stuff to it (like preprending "nice ") without modifying
this code."""
import os
import files
from options import options as o
from prioritymanager import priorityManager

class Decompressor:
    """I decompress a .flac file into a .wav file.

    Public attributes:
        self.cmd  -- the command
                     (might want to prepend 'nice ' to this)
    """
    def __init__(self, inFile, outFile=None, silent=False):
        "Calls flac to decompress a .wav file."
        silentCmd = ''
        if silent: silentCmd= '-s'
        outFileCmd = ''
        if outFile: outFileCmd = '-o "%s"' % (outFile)
        self.cmd = 'flac -d %s %s "%s"' % (outFileCmd, silentCmd, inFile)

    def __call__(self): os.system(self.cmd)

class BatchDecompressor:
    """Decompresses a directoryful of flac files to wav files.
    Since this class doesn't really do anything novel that Decompressor
    doesn't do already, I'm keeping it around just because I don't want to have
    to change the caller around.
    """
    def __init__(self, inDir, outDir=None, silent=False):
        silentCmd = ''
        if silent: silentCmd= '-s'
        self.cmds = []
        for old, new in _makeInputs(inDir, outDir):
            self.cmds.append('flac -d %s -o "%s" "%s"' % (silentCmd, new, old))

    def __call__(self):
        for cmd in self.cmds:
            os.system(priorityManager(cmd))

class Compressor:
    def __init__(self, inFile, outFile=None, compressionLevel=8, args=None):
        if 0 > compressionLevel > 8:
            raise ArgumentError, "compressionLevel must be between 0 and 8"

        if outFile: outFileCmd = ' -o "%s" ' % (outFile)
        else:       outFileCmd = ''

        compressionLevelCmd = ' -%s ' % (compressionLevel)

        if not args: args = ''
        
        self.cmd = 'flac %s %s %s "%s"' % \
                   (compressionLevelCmd, outFileCmd, args, inFile)

    def __call__(self): os.system(self.cmd)
            
def _makeInputs(inDir, outDir):
    """Returns (inFile, outFile) pairs given two directories."""
    inl = os.listdir(inDir)
    inl.sort()
    inl =  [ os.path.join(inDir, x)         for x in inl ]
    outl = [ _swapPath(x, outDir)           for x in inl ]
    outl = [ files.swapExtension(x, '.wav') for x in outl ]
    return zip(inl, outl)

def _swapPath(filename, newPath):
    return os.path.join(newPath, os.path.basename(filename))
    

if __name__ == "__main__":
    decompressBunch('.')
