#!/usr/bin/python
"""Read/write user specific info """
import string, os, re, traceback, time
from ConfigParser import *
from gagz.bugz import konst, bugz
from gagz.utils import *

class Player:

    def __init__(self, username='', datadir=''):
        # get the default login to be the dir name...
        # may get overwritten by the login in the .data file
        if not len(username):
            if not len(datadir):
                datadir = './'
                self.login = os.path.basename(os.getcwd())
            else:
                # make sure it ends on a slash
                if not datadir[-1] == '/':
                    datadir = '%s/' % datadir
                self.login = os.path.basename(datadir)
        else:
            self.login = username
            if not len(datadir):
                datadir = './' + username + '/'

        # note this but don't save it...
        self.dir = os.path.abspath(datadir)[len(konst.kSiteInstallationDir):]

        self.data = datadir + konst.kDataFile
        self.cache = datadir + konst.kSaveLastQueryFile
        self.plotfile = datadir + konst.kPlotScript
        self.chartfile = datadir + konst.kChartFile
        self.name=''
        self.queries={}
        self.history={}
        self.saveHistory = 1
        self.fixrate = 3
        self.plotGraph = 1
        self.drawglidepath = 1
        # only process these queries...
        self.q2run = []
        self.zerobugsdate = time.time()
        if os.access(self.data, os.R_OK):
            self.load()

    def glidepath(self):
        """returns the tuple indicating a glidepath representing the fixrate"""
        gp = []
        frpd = self.fixrate/7.0 # per day fix rate...
        daysleft = (self.zerobugsdate - time.time())/(60*60*24.0)
        # just a straight line--
        for i in [0, 7]:
            gp.append((daysleft+i)*frpd)
        return gp

    def incquery(self, query):
        if self.queries.has_key(query):
            self.queries[query] += 1
        else:
            self.queries[query] = 1

    def load(self):
        cfg = ConfigParser()
        cfg.read(self.data)
        try: self.name = cfg.get('DEFAULT', 'name')
        except NoOptionError: pass
        try: self.login = cfg.get('DEFAULT', 'login')
        except NoOptionError: pass
        try: self.fixrate = cfg.getint('DEFAULT', 'fixrate')
        except NoOptionError: pass
        try: 
            self.zerobugsdate = cfg.getint('DEFAULT', 'zerobugsdate')
            # never accept a past zerobugz date. Always push it by 7 days...
            if self.zerobugsdate < time.time():
                self.zerobugsdate = time.time() + 7*24*60*60
        
        except NoOptionError: pass
        #for q in string.split(cfg.get('DEFAULT', 'queries')):
        b = bugz.Bugz()
        for x in b.queries:
            q = x.short
            try: 
                self.history[q] = cfg.get('DEFAULT', q)
                self.queries[q] = int(string.split(self.history[q])[0])
            except NoOptionError:
                self.history[q] = '0'
                self.queries[q] = 0

    def save(self):
        # insert queries into history
        if self.saveHistory:
            for k in self.queries.keys():
                if self.history.has_key(k):
                    self.history[k] = "%s %s" %( self.queries[k], 
                        self.history[k])
                    if len(self.history[k]) > 30:
                        self.history[k] = self.history[k][:30]
                else:
                    self.history[k] = self.queries[k]
             # trim histories with a max limit (TODO a konst)
                #self.history[k] = string.join(string.split(self.history[k])[:15])

        # I have to write this since ConfigParser write isn't good enuf (yet)
        cf = open(self.data, 'w')
        cf.write('# Auto generated! DO NOT EDIT!\n[DEFAULT]\n')
        cf.write('name: %s\n' % self.name)
        cf.write('login: %s\n' % self.login)
        if len(self.queries):
            cf.write('queries: %s\n' % string.join(self.queries.keys()))
            for k in self.history.keys():
                cf.write('%s: %s\n' % (k, self.history[k]))
        cf.write('fixrate: %d\n' % self.fixrate)
        cf.write('zerobugsdate: %d\n' % int(self.zerobugsdate))
        cf.close()
        # plot the graph as well...
        if self.saveHistory and self.plotGraph:
            from gagz.bugz.plot import plotBugsGraph
            plotBugsGraph(self)

    def process(self, ignoreCache=0):
        """process the queries for this user. If ignoreCache=0 is set then its
possible that this may not do anything."""

        print 'processing %s' % self.name

        if not os.access(self.cache, os.R_OK):
            ignoreCache = 1
            self.saveHistory = 1
            self.plotBugsGraph = 1
       
        if ignoreCache:
            # fetch is fresh...
            #self.saveHistory = 1
            self.plotBugsGraph = 1
            b = bugz.Bugz()
            b.saveLastQuery = self.cache
            b.query(self.login, 1)

        #self.saveHistory = 0
        # check to see if the kSaveLastQueryFile has a lastmod date
        # later than the kDataFile
        # TODO
        #if (os.stat(konst.kSaveLastQueryFile)[8] >
            #os.stat(konst.kDataFile)[8]):
        file = open(self.cache, 'r')
        line = file.readline()
        if line =="":
            return
        pattern = re.compile('stone><nobr>([^<]+)<')
        kw_pattern = re.compile('keywords>([^<]+)<') 

        for x in self.queries.keys():
            self.queries[x] = 0

        lookup = { 
            '---':'untargeted',
            'mozilla1.0.1':'moz101',
            'mozilla1.1alpha':'moz11a',
            'mozilla1.1':'moz11',
            'mozilla0.9.9':'moz99',
            'mozilla1.0':'mozone',
            'Future':'future',
        }
        kw_I_care_about = {
            'nsbeta1+': 'nsbeta1p',
            'nsbeta1': 'nsbeta1',
            'topembed+': 'topembedp',
            'topembed': 'topembed'
        }
        while line != "":
            self.queries['allbugs'] = self.queries['allbugs'] + 1
            m = pattern.search(line)
            if m:
                try:
                    self.incquery(lookup[m.group(1)])
                except KeyError:
                    pass
            # additionally check for keywords as well--
            m = kw_pattern.search(line)
            if m:
                kw_found = map(lambda x: x.strip(),
                    string.split(m.group(1), ','))
                for kw in kw_I_care_about.keys():
                    if kw in kw_found:
                        self.incquery(kw_I_care_about[kw])
            line = file.readline()
        file.close()
        # autosave! maybe make it optional later...
        self.save()

if __name__ == '__main__':
    u = Player('gagan')
    u.name = 'Gagan Saksena'
    u.save()
    u = None
    u = Player('gagan')
    print ('name = %s' % u.name)
