#!/usr/bin/python
#
# arch-tag: a866d56d-a0b1-4090-8924-7f6e31c593f0
#
# Data archive module.
#
import sys
import os
import time

__version__ = '1.1'

# Class to archive the raw data from the NPC.  The data are stored in
# CSV files with one file for each day.  The daily files are named:
#
#    self.basedir/YYYY/MM/npcdataDD.csv
#
# A new file is created at 00:00 local time.
#
class DataArchiver(object):
    def __init__(self, base='/var/tmp', log=sys.stderr.write):
        self.basedir = base
        self.log = log
        self.fd = None
        self._openfile()

    def __getstate__(self):
        d = {}
        d.update(self.__dict__)
        if self.fd:
            self.fd.close()
        d['fd'] = None
        d['log'] = None
        return d

    def __setstate__(self, d):
        self.__dict__.update(d)
        self._openfile()
        
    def _openfile(self):
        if self.fd:
            self.fd.close()
        dir,file = os.path.split(self.filename)
        try:
            os.makedirs(dir)
        except OSError:
            if not os.path.isdir(dir):
                if self.log:
                    self.log('Cannot create archive directory')
                self.fd = None
                return
        self.fd = open(os.path.join(dir, file), 'a')
        
    def _getfilename(self):
        t = time.localtime()
        return self.basedir + '/%04d/%02d/npcdata%02d.csv' % (t[0], t[1], t[2])
    
    def recvSample(self, rec, up):
        """This method implements the NPC Listener interface.  This
        object is registered with the NPC object and each time a new
        sample record is read, this method is called.
        """
        # Is it time to open a new file?
        try:
            if self.fd.name != self.filename:
                self._openfile()
            if self.fd and up:
                self.fd.write(','.join([str(e) for e in rec]) + '\n')
        except IOError, e:
            if self.log:
                self.log('Error updating archive: ' + str(e) + '\n')
            else:
                sys.stderr.write('Error updating archive: ' + str(e) + '\n')
    filename = property(_getfilename, doc='Current filename')

