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

import os
from metadata import Comments, Pragmas
from options import options as o
import wavmaker
from toybag import mash
import files

class VorbisInfo(object):
    """I hold information about how to create an Ogg Vorbis file.

    Attributes:
    comments       -- a Comments object
    pragmas        -- a Pragmas object
    inFile         -- the path to the input .wav file
    outFile        -- the path to the output ogg file
    """

    def __init__(self, inFile, comments=None, pragmas=None):
        self.inFile   = inFile
        self.comments = comments or Comments()
        self.pragmas  = pragmas  or Pragmas()
        self.filenameModifiers   = o.filenameTags

    def __repr__(self):
        return "<VorbisInfo: %s->%s::%s::%s>" % \
               (self.inFile, self.outFile,  self.comments, self.pragmas)

    def _getOrNull(self, key):
        """Attempts to retrieve the first value out of its own comments dict,
        and failing that, returns the null string ('')."""
        try:
            x = self.comments.get(key)[0]
            return x
        except KeyError:
            return ''

    def _getOutFile(self):
        "Find the filename from the title and any overriding pragmas."
        assert len(self.comments) != 0
        name = ''
        try:
            name = self.comments.get('title')[0]

        except KeyError:
            print "Warning: no 'title' comment found in comments file"
            name = files.swapExtension(self.inFile, ".ogg")

        for m in self.filenameModifiers:
            if self._appendTag(m):
                name = _mashTag(name, self._getOrNull(m))

        if name[-1] in ('\r', '\n'): name = name[:-1] # chomp!
        return name + '.ogg'
    
    def _appendTag(self, tag):
        """I determine whether the tag named 'tag' should be appended to
        the filename, and return True if it should be added."""
        v = None
        try:
            v = self.pragmas[tag]
        except KeyError:
            return True # it's not in there, go ahead and add
                
        return v
        

    outFile = property(_getOutFile, None, None,
                       "I'm the name of the file that will be created.")
    
class VorbisInfoList(list):
    """It's a list of VorbisInfos, but with extra bookeeping information.

    In addition to the interface of the builtin list, I have:
    pragmas  -- pragmas that apply to the whole set of VorbisInfos
    """

    def __init__(self, wavMaker, infoAdder):
        """Initializes a new VorbisInfoList."""
        list.__init__(self)
        self.wavMaker = wavMaker
        self.pragmas  = Pragmas()
        for fn in self.wavMaker.getFilenames():
            self.append(VorbisInfo(fn))
        infoAdder.add(self)

def _mashTag(base, tag):
    if len(tag) == 0:
        return base
    else:
        return mash(base, '(%s)' % (tag))
if __name__ == '__main__':
    pass
