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

"""
popis funkcí
"""



def pocty_znacek(seegs):
    """
    Function to get number of marks in each seeg and groups
    Parameters:
    -----------
    seegs - selected subjects
    Returns:
    --------
    pocty - DataFrame with data sorted by type of oscillation, saves as "Dataframes/pocty_znacek_" + str(seegs) + ".pkl"
    pocty_vykresleni - graphical visualisation of DataFrame pocty - saves as "Grafy/Pocty_znacek_" + str(seegs) + ".png"
    Note:
    Remember the length of one signal section (number of samples)
    """

    import seaborn as sns
    import matplotlib.pyplot as plt
    from funkce.D_file_read import read_d_header
    import pandas as pd
    from funkce.nacteni import znaceni, info_o_patologii, channels
    import numpy as np



    # --- počty FR, vFR, uFR
    # seegs = [15, 32, 45, 48]

    zacatek = 0

    index = range(0, len(seegs) * 3)  # odhad velikosti tabulky, později lze udělat přidáváním řádku
    columns = ['seeg', 'FR', 'vFR', 'uFR', 'ch_idx', 'ch_name', 'resection']

    pocty = pd.DataFrame(index=index, columns=columns)
    pocty = pocty.fillna(0)

    for seeg in seegs:
        # nazev, FR, vFR, uFR, df_all_groups = znaceni(seeg)
        nazev, FR, vFR, uFR, df_all_groups = info_o_patologii(seeg)


        # --- načti soubor .d
        sh, xh = read_d_header("../../Data_fnusa/" + str(nazev) + "")

        ch_all, ch_selected, ch_xh_idx, ch_sel_idx = channels(seeg)

        # pocty = pd.DataFrame({'FR': [0, 0], 'vFR': [0, 0], 'uFR': [0, 0], 'ch_idx': [0, 0], 'seeg': [0, 0]})

        ch_pocet = len(ch_sel_idx)

        for i in range(zacatek, zacatek + ch_pocet):  # range(0, ch_pocet):
            pocty.FR[i] = len(FR.loc[FR['ch_idx'] == ch_sel_idx[i % ch_pocet]])
            pocty.vFR[i] = len(vFR.loc[vFR['ch_idx'] == ch_sel_idx[i % ch_pocet]])
            pocty.uFR[i] = len(uFR.loc[uFR['ch_idx'] == ch_sel_idx[i % ch_pocet]])
            # pocty.ch_name[i] = ch
            pocty.ch_idx[i] = ch_sel_idx[i % ch_pocet]
            pocty.ch_name[i] = ch_selected[i % ch_pocet]  # ukazuje warning při ukládání na slice

            pocty.seeg[i] = seeg

            pocty.resection[i] = np.array2string(df_all_groups.resection.where(df_all_groups.ch_name == pocty.ch_name[i]).dropna().unique())    # přidání info o patologii

            # pocty.resection[i] = df_all_groups.resection.where(df_all_groups.ch_name == pocty.ch_name[i]).unique()     # přidání info o patologii



        zacatek += ch_pocet

    # pocty = pocty.drop(pocty.index[6]) # mazání konkrétního řádku
    pocty = pocty.loc[~(pocty == 0).all(axis=1)]  # mazání řádků s nulami

    # řazení dle resekce
    # pocty.resection.unique()
    pocty = pocty.sort_values(by=['seeg', 'resection'])

    max_FR = pocty.FR.max()
    max_vFR = pocty.vFR.max()
    max_uFR = pocty.uFR.max()

    max_graf = [max_FR, max_vFR, max_uFR]  # option number one
    max_graf = [max([max_FR, max_vFR, max_uFR])] * 3  # option number two

    pocty_vykresleni = plt.figure(1, figsize=(10,4))
    plt.subplots_adjust(left=None, bottom=None, right=None, top=0.88, wspace=0.38, hspace=None)

    plt.suptitle('Počet označených úseků u jednotlivých pacientů a v jednotlivých kanálech')
    plt.subplot(1, 3, 1)
    plt.ylim(0, max_graf[0])
    ax1 = sns.barplot(x='ch_name', y="FR", data=pocty, hue='seeg')
    plt.subplot(1, 3, 2)
    plt.ylim(0, max_graf[1])
    ax2 = sns.barplot(x='ch_name', y="vFR", data=pocty, hue='seeg')
    plt.subplot(1, 3, 3)
    plt.ylim(0, max_graf[2])
    ax3 = sns.barplot(x='ch_name', y="uFR", data=pocty, hue='seeg')

    # my_title = 'subjekt'
    # ax1._legend.set_title(my_title)

    # plt.legend(ax1, ax2, ax3, loc='lower left')

    # , hue="seeg", palette="Set2", 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.savefig("Grafy/Frequency_amplitude coupling_" + str(seeg) + "_cas_" + str(time) + ".png")
    # plt.legend()
    # sns.bar.set_width([4, 4, 4])
    # plt.tight_layout()

    pocty_vykresleni.savefig("Grafy/Pocty_znacek_a" + str(seegs) + ".png")
    plt.show()

    # pocty2 = pd.DataFrame()
    # pocty2['seeg'] = pocty.seeg
    # pocty2['counts'] = pocty.FR

    #
    # index = range(0,len(ch_idx))
    # columns = ['seeg', 'pocet_znacek', 'typ', 'ch_idx'] #později ch_name
    # pocty = pd.DataFrame(index=index, columns=columns)
    # pocty = pocty.fillna(0)
    #
    #
    # for i in range(0, len(ch_idx)):
    #     pocty.pocet_znacek[i] = len(FR.loc[FR['ch_idx'] == ch_idx[i]])
    #     pocty.vFR[i] = len(vFR.loc[vFR['ch_idx'] == ch_idx[i]])
    #     pocty.uFR[i] = len(uFR.loc[uFR['ch_idx'] == ch_idx[i]])
    #     pocty.ch_idx[i] = ch_idx[i]
    #     pocty.seeg[i] = seeg
    #
    #
    #
    # import seaborn as sns
    # plt.figure(1)
    # fig_fac = sns.barplot(x='ch_idx', y="FR", data=pocty)#, hue="seeg", palette="Set2", orient="v", width=0.35)
    # plt.show()

    pocty.to_pickle("Dataframes/pocty_znacek_" + str(seegs) + ".pkl")

    return pocty
