import os
import numpy
from tables import *

from datetime import datetime
from dateutil.relativedelta import relativedelta
import time

os.system('cls')

NUM_SIM = 100


def GenerateDates(start_date, end_date):
    result = []
    nxt = start_date
    delta = relativedelta(months=1)
    
    while nxt <= end_date:
        result.append(nxt.toordinal())
        nxt += delta

    return result

ALL_DATES = GenerateDates(datetime(2012, 1, 1), datetime(2062, 1, 1))


# Describe a particle record
class Well(IsDescription):
    name        = StringCol(itemsize=25)  # 25-character string
    results     = Float32Col(shape=(NUM_SIM, len(ALL_DATES), 7)) # array of floats (single-precision)

print len(ALL_DATES)

start = time.time()

# Open a file in 'w'rite mode
fileh = openFile('tutorial_%d.h5'%NUM_SIM, mode = 'w')

# Get the HDF5 root group
root = fileh.root

# Create the groups:
group = fileh.createGroup(root, 'Wells')

# Now, create and fill the tables in Particles group
gparticles = root.Wells

well_names = ['KB%04d'%d for d in xrange(1, 1201)]

table = fileh.createTable("/Wells", 'Wells', Well, "Wells:Results")

# Fill the table with 257 particles
for well in well_names:
    well_hdf = table.row
    # First, assign the values to the Particle record
    well_hdf['name'] = well
    # This injects the Record values
    well_hdf.append()

# Flush the table buffers
table.flush()

print 'H5 file creation time: %0.3f'%(time.time() - start)
print

# Read the records from table '/Events/TEvent3' and select some
table = root.Wells.Wells

start = time.time()

for i in xrange(NUM_SIM):
    for p in table:
        p['results'][i, :, :] = numpy.random.random(size=(len(ALL_DATES), 7))

    table.flush()
    print 'Saving results for simulation %-4d:'%(i+1), time.time() - start

##for p in table:
##    print p[0]

# Finally, close the file (this also will flush all the remaining buffers!)
fileh.close()
