
import fnmatch
import os
import re
import sys
import time

from dirwalker import DirWalker

class RenameWalker(DirWalker):
    def __init__(self, opts):
        self.opts = opts
        self.patterns = [
            # Standard lower case filenames
            [re.compile(r'^([ic]?|.*_)(pn|rn|rma|hlx)'), r'\1hx'],
            # Some producer files use mixed case starting with "RSPN"
            [re.compile(r'^RSPN'), r'HXT'],
            # Some RN-private files got into rnrma*.*
            [re.compile(r'^rnrma([^.]+)\.(.*)'), r'hx\1pr.\2']
            ]

        # Each 'key' is the old filename and each value is an array with
        # the first element being the new filename and the rest of the
        # elements being the subdirs in which that old filename was found
        self.files = {}

    def Visit(self, f):
        if self.opts.has_key('verbose'): print "# Visit(%s)" % f

        fpath = os.path.join(self.baseDir, self.subDir, f)
        if os.path.isdir(fpath): return

        newf = f
        for patt in self.patterns:
            if self.opts.has_key('verbose'):
                print "#...checking %s -> %s" % (patt[0].pattern, patt[1])
            newf = patt[0].sub(patt[1], newf, 1)

        if f != newf:
            if self.files.has_key(f):
                self.files[f].append(os.path.join(self.baseDir, self.subDir))
            else:
                self.files[f] = [newf, os.path.join(self.baseDir, self.subDir)]
