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
from myfunctions import remove_tick_ymarks
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)

    rows = 1
    cols = 3
    #embed()
    grid = gridspec.GridSpec(2,2,hspace = 0.3, width_ratios = [0.7,5], wspace = 0)
    #grid1 = gridspec.GridSpecFromSubplotSpec(rows,cols,subplot_spec=grid[0], wspace=ws, hspace=0.4)#,
    #grid3 = gridspec.GridSpecFromSubplotSpec(rows,cols,subplot_spec=grid[2], wspace=ws, hspace=0.4)#,
    label1 = plt.subplot(grid[0])
    label2 = plt.subplot(grid[2])
    labels = [label1,label2]
    titels = ['binary spikes','Gaussian 0.5 ms']# < 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)
    hd = 0.3
    ws = 0.3
    grid2 = gridspec.GridSpecFromSubplotSpec(rows,cols,subplot_spec=grid[1], wspace=ws, hspace=0.4)#,


    end = ['original']

    color_modul = ['steelblue']*len(end)
    color_mpf = ['crimson']*len(end)
    weight = 'normal'
    y_sum1 = plot_single(lim, data, end, data_all, grid2, color_mpf, color_modul,weight = weight, nrs = [0,1,2],fs_big = fs_big,title = True, xlabel = False, label =False,remove =True)

    grid4 = gridspec.GridSpecFromSubplotSpec(rows, cols, subplot_spec=grid[3], wspace=ws, hspace=0.4)#,

    end = ['05']
    #y_sum = [[]] * len(data)
    y_sum2 = plot_single(lim, data, end, data_all, grid4, color_mpf, color_modul,weight = weight, nrs = [3,4,5],fs_big = fs_big,title = True,  label = True,remove =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, right = 0.96,top = 0.98,bottom = 0.2)

def plot_single(lim, data, end, data_all, grid1, color_mpf, color_modul,tob_lw = 0.5,tob_col = 'black', nr_size = 12, weight = 'bold',nrs = [0,1,2],fs_big = 11, title = True,label = True, xlabel = True,remove =True):
    baseline = pd.read_pickle('data_baseline.pkl')
    y_sum = [[]] * len(data)
    ax = {}
    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

            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, 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)
            ax[0].plot(x, y, color=color_mpf[ee])
            b = baseline[baseline['dataset'] == set]['spike_rate']
            ax[0].axhline(y = b.iloc[0], color = 'grey', linestyle = 'dotted')
            if title == True:
                ax[0].set_title('Cell '+str(dd+1),fontsize = fs_big, fontweight=weight)
            ax[set+e+str(1)] = plt.subplot(grid2[1])
            if (set == data[0]) and (label == True):
                ax[set+e+str(1)].set_ylabel('Modulation ')
                ax[0].set_ylabel('MPF [EODf]')
            if (set == data[0]) and (xlabel == True):
                ax[set + e + str(1)].set_xlabel('EOD multiples')
            #ax[0, dd].set_title(e + ' ms')
            ax[0].set_xlim([0, 4])
            ax[0].text(-0.1, 1.1, string.ascii_uppercase[nrs[dd]], transform=ax[0].transAxes,
                       size=nr_size, weight='bold')

            ax[set+e+str(1)].plot(x, y2, color=color_modul[ee])
            mod_tob = d['result_toblerone_max_' + e]
            ax[set + e + str(1)].plot(x, mod_tob, color=tob_col,linestyle = '--', linewidth = tob_lw)
            # 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]')

            #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[set+e+str(1)] = remove_tick_marks(ax[0])
            ax[0] = remove_tick_marks(ax[0])
            if set != data[0]:
                ax[0] = remove_tick_ymarks(ax[0])
                ax[set + e + str(1)] = remove_tick_ymarks(ax[set+e+str(1)] )
            if remove == True:
                ax[set+e+str(1)] = remove_tick_marks(ax[set+e+str(1)])
            #ax[0].set_ylim([0, lim])
    return y_sum

if __name__ == "__main__":
    data = ['2019-10-21-aa-invivo-1','2019-11-18-af-invivo-1','2019-10-28-aj-invivo-1']
    good_cells = ['2019-10-21-aa-invivo-1']
    medium_cells = ['2019-11-18-am-invivo-1','2019-11-18-aj-invivo-1','2019-10-21-au-invivo-1']
    bad_cells = ['2019-11-18-al-invivo-1','2019-10-28-aj-invivo-1','2019-10-21-ar-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.6)
    #fig, ax = plt.subplots(nrows=2, ncols=3, sharex=True)
    ax = {}
    plot_single_cells(ax, data = data)
    #fig.savefig()
    plt.savefig('differentcells.pdf')
    plt.savefig('../highbeats_pdf/differentcells.pdf')
    # plt.subplots_adjust(left = 0.25)
    plt.show()
    #plt.close()
