import matplotlib.pyplot as plt
import numpy as np
from read_chirp_data import *
from utility import *
from IPython import embed

sampling_rate = 40 #kHz
data_dir = "../data"
dataset = "2018-11-09-ad-invivo-1"

spikes = read_chirp_spikes(os.path.join(data_dir, dataset))
eod = read_chirp_eod(os.path.join(data_dir, dataset))
chirp_times = read_chirp_times(os.path.join(data_dir, dataset))

df_map = {}
for k in spikes.keys():
    df = k[1]
    if df in df_map.keys():
        df_map[df].append(k)
    else:
        df_map[df] = [k]

# make phases together, 12 phases
phase_vec = np.arange(0, 1+1/12, 1/12)
cut_range = np.arange(-50*sampling_rate, 50*sampling_rate, 1)

df_phase_time = {}
df_phase_binary = {}

for deltaf in df_map.keys():
    df_phase_time[deltaf] = {}
    df_phase_binary[deltaf] = {}
    for rep in df_map[deltaf]:
        for phase in spikes[rep]:
            #print(phase)
            for idx in range(len(phase_vec)-1):
                if phase[1] > phase_vec[idx] and phase[1] < phase_vec[idx+1]:

                    spikes_to_cut = np.asarray(spikes[rep][phase])
                    spikes_cut = spikes_to_cut[(spikes_to_cut > -50) & (spikes_to_cut < 50)]
                    spikes_idx = np.round(spikes_cut*sampling_rate)
                    binary_spikes = np.isin(cut_range, spikes_idx)*1

                    if phase_vec[idx] in df_phase_time[deltaf].keys():
                        df_phase_time[deltaf][phase_vec[idx]].append(spikes[rep][phase])
                        df_phase_binary[deltaf][phase_vec[idx]] = np.vstack((df_phase_binary[deltaf][phase_vec[idx]], binary_spikes))
                    else:
                        df_phase_time[deltaf][phase_vec[idx]] = [spikes[rep][phase]]
                        df_phase_binary[deltaf][phase_vec[idx]] = binary_spikes


plot_trials = df_phase_binary['-50Hz'][0.0]
#hist_data = plt.hist(plot_trials)
#ax.plot(hist_data[1][:-1], hist_data[0])

fig, ax = plt.subplots()
for i, trial in enumerate(plot_trials):
    embed()
    exit()
    trial[trial == 0] = np.nan
    ax.scatter(np.ones(len(trial)), trial, marker='|', color='k', size=12)
plt.show()


#mu = 1
#sigma = 1
#time_gauss = np.arange(-4, 4, 1)
#gauss = gaussian(time_gauss, mu, sigma)
# spikes during time vec (00010000001)?

#smoothed_spikes = np.convolve(plot_spikes, gauss, 'same')
#window = np.mean(np.diff(plot_spikes))
#time_vec = np.arange(plot_spikes[0], plot_spikes[-1]+window, window)

#ax.plot(time_vec, smoothed_spikes)

#embed()
#exit()
#hist_data = plt.hist(plot_spikes, bins=np.arange(-200, 400, 20))
#ax.plot(hist_data[1][:-1], hist_data[0])