import os
import fnmatch

class FileSearch:
    """A forward interator that taverses a directory tree and returns files that match a set of patterns.  Patterns should be separated by ','."""
    
    def __init__(self, directory, pattern="*", file=False, dir=False, recursive=True):
        self.stack = [directory]
        self.pattern = pattern.split(',')
        self.files = []
        self.index = 0

        # Default is that if no keywords are passed then
        # both files are directories are returned
        if (not file) and (not dir):
            self.file = True
            self.dir = True
        else:
            self.file = file
            self.dir = dir

        self.recursive=recursive

    def __getitem__(self, index):
        while 1:
            try:
                filename = self.files[self.index]
                self.index = self.index + 1
            except IndexError:
                # pop next directory from stack.
                # IndexError gets called when the stack is empty.
                self.directory = self.stack.pop()
                self.files = os.listdir(self.directory)
                self.index = 0
            else:
                # got a filename
                fullname = os.path.join(self.directory, filename)
                if os.path.isdir(fullname) and not os.path.islink(fullname):
                    if self.recursive:
                        self.stack.append(fullname)

                match = False
                for pattern in self.pattern:
                    if fnmatch.fnmatch(filename, pattern):
                        match = True
                        break
                if match:
                    if self.file and not self.dir:
                        if not os.path.isfile(fullname):
                            continue
                    elif self.dir and not self.file:
                        if not os.path.isdir(fullname):
                            continue
                        
                    return fullname
