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

"""
popis funkcí
"""


def vypocet_metod_a_vykresleni(seegs, okoli):
    """
    Graphical and numerical representation of methods
    Parameters:
        seegs = [15, 32, 45, 48]
        okoli = 150
    -----------
    seegs - selected subjects
    Returns:
    --------
    main_df - dataframe with FR, vFR, uFR and PSE, PAC, FAC, SE
    Note: dříve zde byla chyba v indexování signálu pro výpočet uFR (opraveno 13/02/2019)

    Quick call: main_df = vypocet_metod_a_vykresleni(seegs, okoli)
    If calling only one seeg, seegs must be list, Example: vypocet_metod_a_vykresleni([48], 150)
    """

    import pandas as pd
    import numpy as np
    pd.set_option('display.width', 2000)  # nezalamuj tabulky
    from funkce.nacteni import znaceni, info_o_patologii, channels, signal, sig_df_to_array
    from funkce.pocty_znacek import pocty_znacek
    from funkce.D_file_read import read_d_header
    from fnusa_sigproc.methods_uni import pse, pac, fac
    from pyentrp.entropy import shannon_entropy, sample_entropy
    import matplotlib.pyplot as plt
    from funkce.data_resampling import resample_signals

    # plt.close('all')

    # volba vzorkovací frekvence
    fs = 5000
    time = 2*(okoli/fs)


    # počáteční číslo figure - aby se grafy nepřekrývaly
    fig = 1

    # definice listu s výpočty všech seegs (nutné založení listu pro pozdějiší pd.concat)
    main_df_seegs_list = []


    for seeg in seegs:


        if okoli==60: # předpoklad pro výpočet metod z resamplovaných signálů
            #sig_FR_resampled, sig_vFR_resampled, sig_uFR_resampled = resample_signals()
            sig_FR, sig_vFR, sig_uFR = resample_signals(seeg)
            print('Počítám signály po resamplingu')

        else:
            # načtení signálů
            # získání dat signálu - # načtení offline - načtení z pickle/nový výpočet
            try:
                sig_FR = pd.read_pickle("Dataframes/sig_FR_n" + str(seeg) + "_okoli_" + str(2 * okoli) + ".pkl")
                sig_vFR = pd.read_pickle("Dataframes/sig_vFR_n" + str(seeg) + "_okoli_" + str(2 * okoli) + ".pkl")
                sig_uFR = pd.read_pickle("Dataframes/sig_uFR_n" + str(seeg) + "_okoli_" + str(2 * okoli) + ".pkl")
                print('sig_FR, sig_vFR, sig_uFR načteny ze souboru')
            except (OSError, IOError) as e:
                sig_FR, sig_vFR, sig_uFR = signal(seeg, okoli)
                print('počítám sig_FR, sig_vFR, sig_uFR')


        # načtení nebo výpočet dat
        try:
            main_df = pd.read_pickle("Dataframes/main_df_" + str(seeg)+ "_okoli_" + str(2*okoli) + ".pkl")
            print('main_df načtena ze souboru')

        except (OSError, IOError) as e:

            print('počítám main_df')
            # potřebuji kostru pro výpočet pse, entropie apod.
            nazev, FR, vFR, uFR, df_all_groups = znaceni(seeg)


            # potřebuji i informace o patologii pro přehlednější grafické znázornění
            nazev, FR, vFR, uFR, df_all_groups = info_o_patologii(seeg)





            ### Power spectral entropy - přidání do DF
            vFR['pse'] = 0  # pd.DataFrame(pse_vFR)  # ,'Column2':data[:,1]})
            uFR['pse'] = 0  # pd.DataFrame(pse_uFR)  # ,'Column2':data[:,1]})
            FR['pse'] = 0  # pd.DataFrame(pse_FR)  # ,'Column2':data[:,1]})

            ### Frequency-amplitude coupling
            FR['fac'] = 0
            vFR['fac'] = 0
            uFR['fac'] = 0

            ### Phase-amplitude coupling
            FR['pac'] = 0
            vFR['pac'] = 0
            uFR['pac'] = 0

            ### Shannon entropy
            FR['shannon_entropy'] = 0
            vFR['shannon_entropy'] = 0
            uFR['shannon_entropy'] = 0


            # volba frekvencí pro výpočet fac a pac
            lfc1=1
            hfc1=30

            lfc2=65
            hfc2=180


            # výpočet
            for i in range(0, len(sig_FR.columns)):
                FR.pse.loc[i] = pse(sig_FR[i])
                FR.fac.loc[i] = fac(tuple(sig_FR[i]), fs, lfc1,hfc1,lfc2,hfc2)  #### opraveno: bere to po řádcích, ne po sloupcích
                FR.pac.loc[i] = pac(tuple(sig_FR[i]), fs, lfc1,hfc1,lfc2,hfc2)
                FR.shannon_entropy.loc[i] = shannon_entropy(tuple(sig_FR[i]))

            for i in range(0, len(sig_vFR.columns)):
                vFR.pse.loc[i] = pse(sig_vFR[i])
                vFR.fac.loc[i] = fac(tuple(sig_vFR[i]), fs, lfc1,hfc1,lfc2,hfc2)
                vFR.pac.loc[i] = pac(tuple(sig_vFR[i]), fs, lfc1,hfc1,lfc2,hfc2)
                vFR.shannon_entropy.loc[i] = shannon_entropy(tuple(sig_vFR[i]))

            for i in range(0, len(sig_uFR.columns)):
                uFR.pse.loc[i] = pse(sig_uFR[i])
                uFR.fac.loc[i] = fac(tuple(sig_uFR[i]), fs, lfc1,hfc1,lfc2,hfc2)
                uFR.pac.loc[i] = pac(tuple(sig_uFR[i]), fs, lfc1,hfc1,lfc2,hfc2)
                uFR.shannon_entropy.loc[i] = shannon_entropy(tuple(sig_uFR[i]))


                # kontrola signálu v různých úsecích se stejnou výslednou hodnotou signálu
                # if uFR.shannon_entropy>5.35753 and uFR.shannon_entropy<5.35756:
                #     plt.figure(i)
                #     plt.plot(sig_uFR.loc[i])


            # --- převod sig_df do array (pokud je potřeba)
            # sig_FR_array, sig_vFR_array, sig_uFR_array = sig_df_to_array (sig_FR, sig_vFR, sig_uFR, okoli)


            '''
            ### Sample entropy
            
            
            FR['sample_entropy']=""
            vFR['sample_entropy']=""
            uFR['sample_entropy']=""
            
            for i in range(0,len(sig_FR)):
                FR.sample_entropy.loc[i] = sample_entropy(sig_FR.loc[i], okoli + okoli)
            
            for i in range(0,len(sig_vFR)):
                vFR.sample_entropy.loc[i] = sample_entropy(sig_vFR.loc[i])
            
            for i in range(0,len(sig_uFR)):
                uFR.sample_entropy.loc[i] = sample_entropy(sig_uFR.loc[i])
            '''

            FR['sample_entropy0'] = ""  # FR_sample_entropy
            vFR['sample_entropy0'] = ""  # vFR_sample_entropy
            uFR['sample_entropy0'] = ""  # uFR_sample_entropy

            FR['sample_entropy1'] = ""
            vFR['sample_entropy1'] = ""
            uFR['sample_entropy1'] = ""

            for i in range(0, sig_FR.shape[1]):
                se = sample_entropy(sig_FR[i], 2)

                FR.sample_entropy0.loc[i] = se[0]
                FR.sample_entropy1.loc[i] = se[1]

            for i in range(0, sig_vFR.shape[1]):
                se = sample_entropy(sig_vFR[i], 2)

                vFR.sample_entropy0.loc[i] = se[0]
                vFR.sample_entropy1.loc[i] = se[1]

            for i in range(0, sig_uFR.shape[1]):
                se = sample_entropy(sig_uFR[i], 2)

                uFR.sample_entropy0.loc[i] = se[0]
                uFR.sample_entropy1.loc[i] = se[1]

            # vFR_sample_entropy = sample_entropy(sig_uFR[i], 2)
            # uFR_sample_entropy = sample_entropy(sig_uFR[i], 2)








            ### vykreslení
            import seaborn as sns

            sns.set(style="whitegrid")

            # pse_FR = sns.load_dataset("FR")
            FR['typ'] = 'FR'  # pd.DataFrame('FR',index=FR.index)
            vFR['typ'] = 'vFR'  # 'vFR'
            uFR['typ'] = 'uFR'  # 'uFR'


            main_df: pd.DataFrame = pd.concat([FR, vFR, uFR])
            main_df.reset_index(drop=True, inplace=True)

            main_df.to_pickle("Dataframes/main_df_" + str(seeg) + "_okoli_" + str(2*okoli) + ".pkl")
            # main_df.to_pickle(str(main_df))


        # plt.figure()
        # fig_pse = sns.load_dataset('main_df')
        # ax = sns.boxplot(x=main_df["pse"])

        # seaborn kategoricky odmítá vykreslovat objects, převádím do floatu
        # main_df.pse = main_df.pse  # .astype(np.float64)
        # main_df.fac = main_df.fac  # .astype(np.float64)
        # main_df.pac = main_df.pac  # .astype(np.float64)
        # main_df.shannon_entropy = main_df.shannon_entropy.astype(np.float64)

        try:
            print('Převádím sample_entropy do číselných hodnot')
            print(seeg)
            print(main_df)

            main_df.sample_entropy0 = main_df.sample_entropy0.astype(np.float64)
            main_df.sample_entropy1 = main_df.sample_entropy1.astype(np.float64)
        except (OSError, IOError) as e:
            print('Hodnoty již byly převedeny')



        # řazení aby se v grafech na prvním místě vyskytovalo "no" a na druhém "yes"
        main_df = main_df.sort_values(['group', 'resection'])         # main_df = main_df[order(main_df['typ'], main_df['resection'])]

        # řazení nefunguje ale řazení neuškodí, zkouším unique pro hue_order
        res = sorted(main_df['resection'].unique(), key=str.lower) #reverse=True)


        import seaborn as sns
        import matplotlib.pyplot as plt

        # fig_pse = sns.boxplot(x='pse', data=main_df) #, orient="v", width=0.35)




        plt.figure(fig)
        # fig_pse = sns.boxplot(x='typ', y="pse", data=main_df, palette="Set1", orient="v", width=0.5) # hue="ch_name"
        fig_pse = sns.boxplot(x='typ', y="pse", data=main_df, hue="resection", hue_order=res, palette="Purples", orient="v", width=0.5)  # hue="ch_name", order=["male", "female"], hue_order=[0, 1]
        # fig_pse_sw = sns.swarmplot(x="typ", y="pse", data=main_df, hue="ch_name", dodge=True, color=".3", size=3) 
        plt.title('Power spectral entropy ' + str(seeg))
        # plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
        # plt.legend([line1, line2], ['yep', 'nope'], bbox_to_anchor=[0.5, 0.5],  loc='center', ncol=2)
        plt.savefig("Grafy/Power_spectral_entropy_" + str(seeg) + "_okoli_" + str(2*okoli) + ".png")
        plt.show()

        plt.figure(fig+1)
        # Frequency-amplitude coupling
        fig_fac = sns.boxplot(x='typ', y="fac", data=main_df, hue="resection", hue_order=res, palette="Greens", orient="v", width=0.35)
        # fig_fac_sw = sns.swarmplot(x="typ", y="fac", hue="ch_name", dodge=True, data=main_df, color=".3", size=3)
        plt.title('Frequency-amplitude coupling ' + str(seeg))
        plt.savefig("Grafy/Frequency_amplitude_coupling_" + str(seeg) + "_okoli_" + str(2*okoli) + ".png")
        plt.show()

        # Phase-amplitude coupling
        plt.figure(fig+2)
        fig_pac = sns.boxplot(x='typ', y="pac", data=main_df, hue="resection", hue_order=res, palette="Reds", orient="v", width=0.35)
        # fig_pac_sw = sns.swarmplot(x="typ", y="pac", data=main_df, hue="ch_name", dodge=True, color=".3", size=3)
        plt.title('Phase-amplitude coupling ' + str(seeg))
        plt.savefig("Grafy/Phase_amplitude_coupling_" + str(seeg) + "_okoli_" + str(2*okoli) + ".png")
        plt.show()


        # Shannon entropy
        plt.figure(fig+3)
        fig_shannon = sns.boxplot(x='typ', y="shannon_entropy", data=main_df, hue="resection", hue_order=res, orient="v", width=0.35, palette="Oranges")
        # fig_shannon_sw = sns.swarmplot(x="typ", y="shannon_entropy", data=main_df, hue="ch_name", dodge=True, color=".3", size=3)
        plt.title('Shannon entropy ' + str(seeg))
        plt.savefig("Grafy/Shannon_entropy_" + str(seeg) + "_okoli_" + str(2*okoli) + ".png")
        plt.show()

        #Sample entropy0
        plt.figure(fig+4)
        fig_sample0 = sns.boxplot(x='typ', y="sample_entropy0", data=main_df, hue="resection", hue_order=res, orient="v", width=0.35, palette="Blues")
        plt.title('Sample_entropy0 ' + str(seeg))
        plt.savefig("Grafy/Sample_entropy0_" + str(seeg) + "_okoli_" + str(2*okoli) + ".png")
        plt.show()


        #Sample entropy1
        plt.figure(fig+5)
        fig_sample0 = sns.boxplot(x='typ', y="sample_entropy1", data=main_df, hue="resection", hue_order=res, orient="v", width=0.35, palette="Greys")
        plt.title('Sample_entropy1 ' + str(seeg))
        plt.savefig("Grafy/Sample_entropy1_" + str(seeg) + "_okoli_" + str(2*okoli) + ".png")
        plt.show()






        """
        Vykreslení bez rozlišení oscilace
        """

        # pse
        n_subfig_rows = 2
        n_subfig = 3

        plt.figure(fig+30, figsize=(9,9)) #20,5/9,9
        plt.suptitle('Pacient č. ' +str(seeg)+'')

        plt.subplot(n_subfig_rows,n_subfig,1)
        fig_pse = sns.boxplot(x='resection', y="pse", data=main_df, order=res, palette="Purples", orient="v", width=0.5)  # hue="ch_name", order=["male", "female"], hue_order=[0, 1]
        plt.title('Power spectral entropy ') # + str(seeg))
        #plt.savefig("Grafy/Power_spectral_entropy_bez_rozliseni_typu_oscilace_" + str(seeg) + "_okoli_" + str(2*okoli) + ".png")
        #plt.show()


        # Frequency-amplitude coupling
        plt.subplot(n_subfig_rows,n_subfig,2)
        fig_fac = sns.boxplot(x='resection', y="fac", data=main_df, order=res, palette="Greens", orient="v", width=0.35)
        plt.title('Frequency-amplitude coupling ') #  + str(seeg))
        #plt.savefig("Grafy/Frequency_amplitude_coupling_bez_rozliseni_typu_oscilace_" + str(seeg) + "_okoli_" + str(2*okoli) + ".png")
        #plt.show()


        # Phase-amplitude coupling
        plt.subplot(n_subfig_rows,n_subfig,3)
        fig_pac = sns.boxplot(x='resection', y="pac", data=main_df, order=res, palette="Reds", orient="v", width=0.35)
        plt.title('Phase-amplitude coupling ') #  + str(seeg))
        #plt.savefig("Grafy/Phase_amplitude_coupling_bez_rozliseni_typu_oscilace_" + str(seeg) + "_okoli_" + str(2*okoli) + ".png")
        #plt.show()


        # Shannon entropy
        plt.subplot(n_subfig_rows,n_subfig,4)
        fig_shannon = sns.boxplot(x='resection', y="shannon_entropy", data=main_df, order=res, orient="v", width=0.35, palette="Oranges")
        plt.title('Shannon entropy ') #  + str(seeg))
        #plt.savefig("Grafy/Shannon_entropy_bez_rozliseni_typu_oscilace_" + str(seeg) + "_okoli_" + str(2*okoli) + ".png")
        #plt.show()

        #Sample entropy0
        plt.subplot(n_subfig_rows,n_subfig,5)
        fig_sample0 = sns.boxplot(x='resection', y="sample_entropy0", data=main_df, order=res, orient="v", width=0.35, palette="Blues")
        plt.title('Sample_entropy0 ') #  + str(seeg))
        #plt.savefig("Grafy/Sample_entropy0_bez_rozliseni_typu_oscilace_" + str(seeg) + "_okoli_" + str(2*okoli) + ".png")
        #plt.show()

        #Sample entropy1
        plt.subplot(n_subfig_rows,n_subfig,6)
        fig_sample0 = sns.boxplot(x='resection', y="sample_entropy1", data=main_df, order=res, orient="v", width=0.35, palette="Greys")
        plt.title('Sample_entropy1 ') #  + str(seeg))
        # plt.savefig("Grafy/Sample_entropy1_bez_rozliseni_typu_oscilace_" + str(seeg) + "_okoli_" + str(2*okoli) + ".png")
        # plt.show()

        plt.tight_layout()

        plt.subplots_adjust(top=0.85)
        plt.show()

        plt.savefig("Grafy/PSE_PAC_FAC_SE_SE0_SE1_bez_rozliseni_typu_oscilace_" + str(seeg) + "_okoli_" + str(2*okoli) + ".png")






        # indexace figures, aby se nepřekreslovaly přes sebe
        fig = fig + 6

        main_df_seegs_list.append(main_df)






    """
    vykreslování souhrnných informací o datech:
    souhrnný graf pro rozlišení typu a resekce, 
    souhrnný graf pro rozlišení typu, 
    souhrnný graf pro rozlišení resekce,     
    """


    if len(seegs)==1:
        main_df_seegs = main_df


    if len(seegs)>1:
        main_df_seegs = pd.concat(main_df_seegs_list)
        main_df_seegs = main_df_seegs.reset_index(drop=True)


    n_subfig = 6

    plt.figure(fig+10, figsize=(20,10))
    plt.suptitle('Pacienti ' +str(seegs)+'')


    plt.subplot(1,n_subfig,1)
    fig_pse = sns.boxplot(x='typ', y="pse", data=main_df_seegs, hue="resection", hue_order=res, orient="v", width=0.5, palette="Purples")  # palette = Set1 hue="ch_name", order=["male", "female"], hue_order=[0, 1]
    plt.title('Power spectral entropy ')

    # Frequency-amplitude coupling
    plt.subplot(1,n_subfig,2)
    fig_fac = sns.boxplot(x='typ', y="fac", data=main_df_seegs, hue="resection", hue_order=res, palette="Greens", orient="v", width=0.35)
    plt.title('Frequency-amplitude coupling ')

    # Phase-amplitude coupling
    plt.subplot(1,n_subfig,3)
    fig_pac = sns.boxplot(x='typ', y="pac", data=main_df_seegs, hue="resection", hue_order=res, palette="Reds", orient="v", width=0.35)
    plt.title('Phase-amplitude coupling ')

    plt.subplot(1,n_subfig,4)
    fig_shannon = sns.boxplot(x='typ', y="shannon_entropy", data=main_df_seegs, hue="resection", palette="Oranges", hue_order=res, orient="v", width=0.35)
    plt.title('Shannon entropy ')

    plt.subplot(1,n_subfig, 5)
    fig_sample0 = sns.boxplot(x='typ', y="sample_entropy0", data=main_df_seegs, hue="resection", hue_order=res, orient="v", width=0.35,  palette="Blues")
    plt.title('Sample entropy0 ')


    plt.subplot(1, n_subfig, 6)
    fig_sample1 = sns.boxplot(x='typ', y="sample_entropy1", data=main_df_seegs, hue="resection", hue_order=res, orient="v", width=0.35,  palette="Greys")
    plt.title('Sample entropy1 ')

    plt.tight_layout()

    plt.subplots_adjust(top=0.85)
    plt.show()


    # maximalizace okna
    # mng = plt.get_current_fig_manager()
    # mng.resize(*mng.window.maxsize())

    # zobrazení a uložení
    plt.show()
    plt.savefig("Grafy/PSE_FAC_PAC_SE_SE0_SE1" + str(seegs) + "_okoli_" + str(2*okoli) + ".png")



    """
    Vykreslení bez rozlišení resekce
    """

    n_subfig_rows = 2
    n_subfig = 3

    plt.figure(fig+20, figsize=(9,9)) #20,5/9,9
    plt.suptitle('Pacienti ' +str(seegs)+'')

    # Power spectral entropy
    plt.subplot(n_subfig_rows,n_subfig,1)
    fig_pse = sns.boxplot(x='typ', y="pse", data=main_df_seegs, orient="v", width=0.5, palette="Purples")  # hue="ch_name", order=["male", "female"], hue_order=[0, 1]
    plt.title('Power spectral entropy ')

    # Frequency-amplitude coupling
    plt.subplot(n_subfig_rows,n_subfig,2)
    fig_fac = sns.boxplot(x='typ', y="fac", data=main_df_seegs, orient="v", width=0.35, palette="Greens")
    plt.title('Frequency-amplitude coupling ')

    # Phase-amplitude coupling
    plt.subplot(n_subfig_rows,n_subfig,3)
    fig_pac = sns.boxplot(x='typ', y="pac", data=main_df_seegs,  orient="v", width=0.35, palette="Reds")
    plt.title('Phase-amplitude coupling ')

    plt.subplot(n_subfig_rows,n_subfig,4)
    fig_shannon = sns.boxplot(x='typ', y="shannon_entropy", data=main_df_seegs, orient="v", width=0.35, palette="Oranges")
    plt.title('Shannon entropy ')

    plt.subplot(n_subfig_rows,n_subfig, 5)
    fig_sample0 = sns.boxplot(x='typ', y="sample_entropy0", data=main_df_seegs, orient="v", width=0.35,  palette="Blues")
    plt.title('Sample entropy0 ')


    plt.subplot(n_subfig_rows, n_subfig, 6)
    fig_sample1 = sns.boxplot(x='typ', y="sample_entropy1", data=main_df_seegs, orient="v", width=0.35,  palette="Greys")
    plt.title('Sample entropy1 ')

    plt.tight_layout()

    plt.subplots_adjust(top=0.85)
    plt.show()

    plt.savefig("Grafy/PSE_FAC_PAC_SE_SE0_SE1_no_resection_" + str(seegs) + "_okoli_" + str(2*okoli) + ".png")
    plt.savefig("Grafy/PSE_FAC_PAC_SE_SE0_SE1_no_resection_.png")






    plt.pause(0.001)

    '''
    # možnost zavření všech oken po vykreslení a uložení

    close = float( input("Close all figures? (1/0): ") )

    if close == 1:
        # for f in range(1,fig):
        plt.close('all')
        # vyskočí hodne grafů - zavřít??
        # import matplotlib.pyplot as plt
        # plt.close('all')

    elif close == 0:
         print('Okay')
    elif close != 1 or close != 0:
         print('Next time write 1 or 0')
    '''

    return main_df







