#!/usr/bin/python
"""Process a team based on its preferences """
import string, os, re, traceback
from ConfigParser import *
from gagz.bugz import player, konst
from gagz.utils import *

class Team(player.Player):

    def __init__(self, teamname='', datadir='./'):
        self.team=[]
        player.Player.__init__(self, teamname, datadir)

    def load(self):
        player.Player.load(self)
        cfg = ConfigParser()
        cfg.read(self.data)
        try: self.team= string.split(cfg.get('DEFAULT', 'team'))
        except NoOptionError: pass

    def save(self):
        player.Player.save(self)
        self.team.sort()
        # most of the file is written by player.Player's save
        # so only need to append the differences from that one
        cf = open(self.data, 'a')
        cf.write('team:%s\n' % string.join(self.team))
        cf.close()


    def process(self, ignoreCache=0):
        """process the queries for this team"""
       
        # optimize by running the query with all the users and then
        # filter them out based on that...

        # if cache file not found then...
        if not os.access(self.cache, os.F_OK):
            ignoreCache = 1

        wholeteam = string.join(map(lambda x: player.Player(x).login, 
            self.team), '|')

        if ignoreCache:
            from gagz.bugz.bugz import Bugz
            b = Bugz()
            b.saveLastQuery = self.cache
            b.query(wholeteam, 1)

        datafiles = {}
        for k in self.team:
            datafiles[player.Player(k).login] = open(k + '/' +
                konst.kSaveLastQueryFile, 'w')

        file = open(self.cache, 'r')
        line = file.readline()
        allcount = 0
        pattern = re.compile(wholeteam)
        while line != "":
            allcount = allcount +1
            m = pattern.search(line)
            if m:
                if datafiles.has_key(m.group()):
                    datafiles[m.group()].write(line)
                else:
                    print 'filtering failed for %s' % m.group()
            line = file.readline()

        for k in datafiles.keys():
            datafiles[k].close()
        file.close()

        # whether we used the cache or not... process team and force them to
        # use their cache since we would have rewritten their lastqueryfiles
        for p in self.team:
            u = player.Player(p)
            # don't save it in history if this is a cached copy
            # u.saveHistory = ignoreCache
            u.process()

        #This will parse the results one more time for our records.
        # TODO later on this should be the only other thing self.process should
        # run
        player.Player.process(self)

if __name__ == '__main__':
    t = Team()
    print t.name
    print t.team
