#/usr/bin/env python

from tables import *
#from py4cs.NumPyDB import *


class FileTable(object):
    # What kinds of filetype are implemented ?
    IMPLEMENTED = ('hdf5','text','arrPickle','shelve')
    
    def __new__(self,filename,filetype='hdf5',mode='store'):
        """
        Returns an instance of type filetype.

        At this time, ASCII file, HDF5 and shelve are implemented.
        """
        if filetype in FileTable.IMPLEMENTED:
            a = eval('NumPyDB_'+filetype+'(filename,mode)')
            return a
        else:
            raise TypeError,'Unsupported filetype: %s' % (filetype,)

class NumPyDB_hdf5:
    def __init__(self,filename,mode='store'):
        """
        Open an HDF5 file named filename.
        """
        if mode == 'store':
            self.fd = filename+'.h5'
            fd = openFile(self.fd,'w');fd.close()
            self.prepare_DataStruct()
        
    def prepare_DataStruct(self):
        """
        Initialize a tables.Table object to store every computed values.

        The Table columns are given by self_content_description.
        """
        ## Prepare the content of the savefile (if it exists).
        fd = openFile(self.fd,'a')
        savedescription = {'time':Col('Float'),
                           'uval':Col('Float',shape=(131,))}
        #self._savefile.prepare_DataStruct(savedescription,
        #                                  saveoptions['simul_name'])
        # Create the unit element to store and then create the EArray object.
        fd.createTable(\
                fd.root,
                self.fd[:-3],
                savedescription,
                filters = Filters(complevel=1)) # reduce disk occ.
        fd.close()

    def dump(self,data,identifier):
        """
        Save the current computed values to an h5file.

        Before invoking this method, you have to call prepare_savedata to
        initialize the needed objets.
        """
        fd = openFile(self.fd,'a')
        table = eval('fd.root.'+self.fd[:-3])
        current_row = table.row
        current_row['uval'] = data
        current_row['time'] = identifier
        current_row.append()
        table.flush()
        fd.close()

if __name__ == '__main__':
    import MLab,time
    fd = NumPyDB_hdf5('test_NumPyDB')
    for ii in ['hdf5',]:#['text','arrPickle','hdf5','shelve']:
        t1 = time.clock()
        for jj in xrange(100):
            vector = MLab.rand(131)
            fd.dump(vector[:],jj)
        print ii+': %g' % (time.clock()-t1)
