#!/usr/bin/env python
# -*- coding: utf-8 -*-

from datetime import date, datetime, timedelta
import h5py
import time
import numpy as np
import os
from astropy.time import Time

from epics import sensor_read

def create_hdf_file(channels):

    period = 1
    dataset_size = 1440 * 60/period + 60/period 

    this_day_in_tucson = Time.now().isot.split('T')[0]

    telemetry_path =  '/data/telemetry/'
    telemetry_path += this_day_in_tucson + '/'

    if "temperature" in channels[0]:
        ext = ".temperature"
    else:
        ext = ".pressure"
        
    telemetry_file =  telemetry_path + "SASHA." + this_day_in_tucson + ext + ".hdf5" 
    
    if not os.path.exists(telemetry_path):
        print("{} not exists. Creating...".format(telemetry_path) )
        os.mkdir(telemetry_path)
        
    if not os.path.isfile(telemetry_file):
        print("{} not exists. Creating...".format(telemetry_file) )
        os.mknod(telemetry_file)
    
        with h5py.File(telemetry_file, 'w') as h5File:
            print("Opening {}".format(telemetry_file) )
            h5File.create_dataset("datetime", (0,1), maxshape=(None, 1), dtype='26S')
            
            dset = h5File["datetime"]
            dset.attrs["Stream name"] = "datetime"
            dset.attrs["Table count"] = 1
            
            for channel in channels:
                h5File.create_dataset(channel, (0,1), maxshape=(None, 1), fillvalue=-1)
        
                dset = h5File[channel]
                dset.attrs["Stream name"] = channel
                dset.attrs["Table count"] = 1

    return telemetry_file


def write_to_hdf_file(channels, values):
    
    telemetry_file = create_hdf_file(channels)
        
    with h5py.File(telemetry_file, 'a') as h5File:
        
        now = Time.now().isot
        dataset = h5File["datetime"]
        dataset.resize((dataset.shape[0] + 1), axis=0)
        dataset[-1:] = now
        #dataset.resize((dataset.shape[0] + len(now)), axis=0)
        #dataset[-len(now):] = now
        
        for channel,value in zip(channels,values):
            
            dataset = h5File[channel]
            dataset.resize((dataset.shape[0] + 1), axis=0)            
            dataset[-1:] = value

            
def run():

    # Send temperatures
    channels = ["shark:nir:cv:temperature1",
                "shark:nir:cv:temperature2",
                "shark:nir:cv:temperature3",
                "shark:nir:cv:temperature4"]
    temperatures = sensor_read("sharknir_temp.sensor.value")
    write_to_hdf_file(channels, temperatures)
    
    # Send pressure
    channels = ["shark:nir:cv:pressure"]
    pressure = sensor_read("sharknir_pres1.sensor.value")
    write_to_hdf_file(channels, temperatures)


if __name__ == "__main__":
    '''If running from command line'''
        
    run()
