import nixio as nix
import os
import numpy as np
from IPython import embed

def read_baseline_eod(dataset):
    base = dataset.split(os.path.sep)[-1] + ".nix"
    nix_file = nix.File.open(os.path.join(dataset, base), nix.FileMode.ReadOnly)
    b = nix_file.blocks[0]
    if 'BaselineActivity_1' in b.tags:
        t = b.tags["BaselineActivity_1"]
    elif "BaselineActivity_2" in b.tags:
        t = b.tags["BaselineActivity_2"]
    else:
        f.close()
        return [],[]
    eod_da = b.data_arrays["LocalEOD-1"]
    eod = t.retrieve_data("LocalEOD-1")[:]
    time = np.asarray(eod_da.dimensions[0].axis(len(eod)))
    nix_file.close()
    return time, eod


def read_baseline_spikes(dataset):
    base = dataset.split(os.path.sep)[-1] + ".nix"
    nix_file = nix.File.open(os.path.join(dataset, base), nix.FileMode.ReadOnly)
    b = nix_file.blocks[0]
    if 'BaselineActivity_1' in b.tags:
        t = b.tags["BaselineActivity_1"]
    elif "BaselineActivity_2" in b.tags:
        t = b.tags["BaselineActivity_2"]
    else:
        f.close()
        return [],[]
    spikes_da = b.data_arrays["Spikes-1"]
    spike_times = spikes_da[:spikes_da.shape[0]-5000]
    baseline_spikes = spike_times[(spike_times > t.position[0]) & (spike_times < (t.position[0] + t.extent[0]))]
    nix_file.close()
    return baseline_spikes
    

if __name__ == "__main__":
    data_dir = "../data"
    dataset = "2018-11-09-ad-invivo-1"
    time, eod = read_baseline_eod(os.path.join(data_dir, dataset))
    spike_times = read_baseline_spikes(os.path.join(data_dir, dataset))

