import nixio as nix
import os
from IPython import embed
#from utility import *
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import matplotlib.mlab as ml
import scipy.integrate as si
from scipy.ndimage import gaussian_filter
from IPython import embed
from myfunctions import *
#from axes import label_axes, labelaxes_params
from myfunctions import auto_rows
from myfunctions import default_settings
from myfunctions import remove_tick_marks
import matplotlib.gridspec as gridspec
import string

def plot_single_cells(ax, data = ['2019-10-21-aa-invivo-1','2019-11-18-af-invivo-1','2019-10-28-aj-invivo-1']):
    colors = ['#BA2D22', '#F47F17', '#AAB71B', '#3673A4', '#53379B']
    # labelaxes_params(xoffs=-3, yoffs=0, labels='A', font=dict(fontweight='bold'))
    #baseline = pd.read_pickle('data_baseline.pkl')
    #data_beat = pd.read_pickle('data_beat.pkl')
    data_all = pd.read_pickle('beat_results_smoothed.pkl')
    #data = np.unique(data_all['dataset'])[0]
    #data = np.unique(data_all['dataset'])
    end = ['original', '005','05', '2' ]

    end = ['original','005']
    y_sum = [[]]*len(data)*len(end)
    counter = 0
    for dd,set in enumerate(data):
        for ee, e in enumerate(end):
            d = data_all[data_all['dataset'] == set]
            #x = d['delta_f'] / d['eodf'] + 1
            #embed()
            #y = d['result_frequency_' + e]
            y = d['result_amplitude_max_' + e]
            #y2 = d['result_amplitude_max_' + e]
            y_sum[counter] = np.nanmax(y)
            counter += 1
            #print(np.nanmax(y))
    #embed()
    lim = np.max(y_sum)

    #embed()
    grid = gridspec.GridSpec(1,3,width_ratios = [0.2,4,4],)
    grid0 = gridspec.GridSpecFromSubplotSpec(3, 1, subplot_spec=grid[0], wspace=0.02, hspace=0.1)  # ,

    label1 = plt.subplot(grid0[0])
    label2 = plt.subplot(grid0[1])
    label3 = plt.subplot(grid0[2])
    labels = [label1,label2,label3]
    titels = ['Cell 1','Cell 2','Cell 3']# < 0.5 EODf,with 0.5 ms wide
    fs_big = 11
    weight = 'bold'
    for ll,l in enumerate(labels):
        #embed()
        l.spines['right'].set_visible(False)
        l.spines['left'].set_visible(False)
        l.spines['top'].set_visible(False)
        l.spines['bottom'].set_visible(False)
        l.set_yticks([])
        l.set_xticks([])
        l.set_ylabel(titels[ll],labelpad = 15, fontsize = fs_big, fontweight=weight, rotation = 0)
    hd = 0.3
    grid1 = gridspec.GridSpecFromSubplotSpec(3,1,subplot_spec=grid[1], wspace=0.02, hspace=0.3)#,


    end = ['original']

    color_modul1 = 'steelblue'
    color_mpf = 'red'

    y_sum1,moduls = plot_single(lim, data, end, data_all, grid1, color_mpf, color_modul1,arrows = False,nrs = [0,1,2], title = 'Binary spike trains',xlabel = True,yticks = False)

    grid2 = gridspec.GridSpecFromSubplotSpec(3, 1, subplot_spec=grid[2], wspace=0.02, hspace=0.4)#,

    end = ['05']
    end = ['2']
    #y_sum = [[]] * len(data)

    color_mpf = 'red'
    color_modul = 'royalblue'
    color_modul = 'steelblue'
    color_mpf = 'darkred'
    color_mpf = 'tomato'
    color_mpf = 'red'
    alpha = 1
    y_sum2, moduls = plot_single(lim, data, end, data_all, grid2, color_mpf, color_modul,color_upper = color_modul1, alpha = alpha, arrows = True, mods = moduls, nrs = [3,4,5], title = '2 ms Gaussian',xlabel = False)

    #for dd, d in enumerate(data):
        # embed()
        #embed()
        #ax[1].set_ylim([0, np.nanmax([y_sum1,y_sum2])])
        #ax[1, dd].set_ylim([0, 350])
    plt.subplots_adjust(wspace = 0.4,left = 0.1,top = 0.94, right = 0.96,bottom = 0.1)

def plot_single(lim, data, end, data_all, grid1, color_mpf, color_modul,alpha = 1, color_upper = 'grey',mods = [],tob_col = 'black', tob_lw = '0.8', arrows = True, nr_size = 12, nrs = [0,1,2], xlabel = True,title = '',yticks =True):
    baseline = pd.read_pickle('data_baseline.pkl')
    y_sum = [[]] * len(data)
    ax = {}
    moduls = [[]]*len(data)
    for dd,set in enumerate(data):
        for ee, e in enumerate(end):
            d = data_all[data_all['dataset'] == set]
            x = d['delta_f'] / d['eodf'] + 1
            #embed()
            y = d['result_frequency_' + e]
            y2 = d['result_amplitude_max_' + e]
            y_sum[dd] = np.nanmax(y)
            ff = d['delta_f'] / d['eodf'] + 1
            fe = d['beat_corr']
            #fig.suptitle(set)
            grid2 = gridspec.GridSpecFromSubplotSpec(2, 1, height_ratios = [1,2], subplot_spec=grid1[dd], wspace=0.02, hspace=0.2)  # ,
            ax[0] = plt.subplot(grid2[0])
            ax[0].plot(ff, fe, color=tob_col,linestyle = '--', linewidth = tob_lw, zorder = 2)
            ax[0].plot(x, y, color=color_mpf, zorder = 3,alpha = alpha)
            ax[0].text(-0.1, 1.1, string.ascii_uppercase[nrs[dd]], transform=ax[0].transAxes,
                       size=nr_size, weight='bold')
            b = baseline[baseline['dataset'] == set]['spike_rate']
            ax[0].axhline(y = b.iloc[0], color = 'grey', linestyle = 'dotted', zorder = 1)
            if dd == 0:
                plt.title(title)
            ax[set+e+str(1)] = plt.subplot(grid2[1])
            #ax[0, dd].set_title(e + ' ms')
            ax[0].set_xlim([0, 4])
            #if (e == 2) and xlabel == True:
            ax[set+e+str(1)].plot(x, y2, color=color_modul,alpha = alpha,zorder = 2)
            mod_tob = d['result_toblerone_max_' + e]
            ax[set + e + str(1)].plot(x, mod_tob, color=tob_col,linestyle = '--', alpha = alpha,linewidth = tob_lw, zorder = 1)
            if arrows == True:
                plt.fill_between(x, y2,mods[dd], color = 'gainsboro', edgecolor= 'grey',zorder = 1)
                plt.plot(x, mods[dd], alpha = 0.6, color = color_upper)#linewidth = 0.4,
                array = [0.65,  ]#2.651.65,
                small_arrows = True
                if small_arrows == True:
                    for a in range(len(array)):
                        #embed()
                        pos = np.argmin(np.abs(np.array(x)-array[a]))
                        x_present = np.array(x)[pos]
                        y2 = np.array(y2)
                        #embed()
                        pos_change = 2
                        nr = 19
                        nr2 = 5
                        #embed()
                        if (np.array(mods[dd])[pos]-y2[pos])>nr:
                            plt.plot([x_present, x_present],
                                     [y2[pos] + nr, np.max(np.array(mods[dd])[pos - pos_change:pos + pos_change])-nr2],
                                     color='black')
                            plt.scatter([x_present],[y2[pos]+nr], marker = 'v',s = 10, color='black')
            moduls[dd] = y2
            # ax[1,0].set_ylabel('modulation depth [Hz]')
            #ax[2, ee].plot(x, y2, color=colors[0])
            #ax[2, 0].set_ylabel('         modulation depth [Hz]')
            # ax[1,ee].annotate("", xy=(0.53, 16.83), xytext=(0.53, 17.33), arrowprops=dict(arrowstyle="->"))
            # ax[1,ee].annotate("", xy=(1.51, 16.83), xytext=(1.51, 17.33), arrowprops=dict(arrowstyle="->"))

            #ax[1, 0].set_xlabel('stimulus frequency [EODf]')
            if (dd == 2) and xlabel == True:
                ax[set+e+str(1)].set_xlabel('stimulus frequency [EODf]')
                ax[0].set_ylabel('[Hz]')
                ax[set + e + str(1)].set_ylabel('Modulation ')
            #ax[1, 2].set_xlabel('stimulus frequency [EODf]')
            #ax[2, 3].set_xlabel('stimulus frequency [EODf]')

            ax[0].spines['right'].set_visible(False)
            ax[0].spines['top'].set_visible(False)
            ax[set+e+str(1)].spines['right'].set_visible(False)
            ax[set+e+str(1)].spines['top'].set_visible(False)
            #ax[2, ee].spines['right'].set_visible(False)
            #ax[2, ee].spines['top'].set_visible(False)
            ax[0].set_xlim([0, 5])
            ax[set+e+str(1)].set_xlim([0, 5])
            #plt.tight_layout()
            # fig.label_axes()
            ax[set+e+str(1)].set_ylim([0, lim])
            #ax[0].set_ylim([0, 240])
            ax[0] = remove_tick_marks(ax[0])
            if set != data[-1]:
                ax[set+e+str(1)] = remove_tick_marks(ax[set+e+str(1)])
            if yticks == True:
                remove_tick_ymarks(ax[set+e+str(1)])
                remove_tick_ymarks(ax[0])
            #ax[0].set_ylim([0, lim])
    return y_sum, moduls

if __name__ == "__main__":
    data = ['2019-10-21-aa-invivo-1','2019-11-18-af-invivo-1','2019-10-28-aj-invivo-1']
    data = ['2019-10-21-aa-invivo-1', '2019-10-21-au-invivo-1', '2019-10-28-aj-invivo-1']
    data = ['2019-09-23-ad-invivo-1', '2019-10-21-au-invivo-1', '2019-10-28-aj-invivo-1']
    data = ['2019-10-21-aa-invivo-1','2019-11-18-ac-invivo-1', '2019-10-28-aj-invivo-1']#'2019-11-18-ag-invivo-1''2019-11-18-ab-invivo-1'
    data = ['2019-11-18-ac-invivo-1','2019-11-08-aa-invivo-1', '2019-10-28-aj-invivo-1']
    default_settings(data,intermediate_width = 6.28,intermediate_length = 6)
    #fig, ax = plt.subplots(nrows=2, ncols=3, sharex=True)
    ax = {}
    plot_single_cells(ax, data = data)
    #fig.savefig()
    plt.savefig('differentcells_trans.pdf')
    plt.savefig('../highbeats_pdf/differentcells_trans.pdf')
    # plt.subplots_adjust(left = 0.25)
    plt.show()
    #plt.close()
