#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-

import numpy as np
from sklearn import metrics
import matplotlib.pyplot as plt
import seaborn as sns
from funkce2 import *
import sys
import pandas as pd

"""--------------------
POPIS:
funkce pro výpočet hodnot specificity a senzitivity
-------------------------------------------------------------------------------------"""
def roc(database, seeg, i, columns):

    #--- načtení DataFrame z MySQL workbench
    ll_df = get_data(database, seeg, i, columns)

    #--- funkce pro součet detekcí v jednotlivých kanálech
    count_df = count_hfo_events(ll_df)

    # SELECT * FROM reviewed_events.seizures;
    ll_reviewed_data = get_reviewed_data(seeg)

    # print 'Pocet Irritative zone kanalu u pacienta c.%s je' %seeg, len(ll_reviewed_data[ll_reviewed_data.onset_channel=="IrritativeZone"])
    # print 'Pocet SOZ kanalu u pacienta c.%s je' %seeg, len(ll_reviewed_data[ll_reviewed_data.onset_channel=="SOZ"])
    # print 'Pocet NON_SOZ kanalu u pacienta c.%s je' %seeg, len(ll_reviewed_data[ll_reviewed_data.onset_channel=="NON_SOZ"])

    IZ_count=len(ll_reviewed_data[ll_reviewed_data.onset_channel=="IrritativeZone"])
    SOZ_count=len(ll_reviewed_data[ll_reviewed_data.onset_channel=="SOZ"])
    NON_SOZ_count=len(ll_reviewed_data[ll_reviewed_data.onset_channel=="NON_SOZ"])

    print ('Count of channels, patient number %s: \n IrritativeZone: %s \n SOZ: %s \n NON SOZ: %s') %(seeg, IZ_count, SOZ_count, NON_SOZ_count)

    count_df['soz_info'] = ''
    count_df['total_count'] = ''

    SOZ_channels = list(ll_reviewed_data.loc[(ll_reviewed_data.onset_channel == "SOZ"), "channel_name"])
    IZ_channels = list(ll_reviewed_data.loc[(ll_reviewed_data.onset_channel == "IrritativeZone"), "channel_name"])

    #vytvoření tabulky s počty HFO events

    for i in range(0, len(count_df)):  # count_df.soz_info)):

        count_df.loc[i, 'total_count'] = sum([count_df.SOZ_count[i], count_df.IZ_count[i], count_df.NON_SOZ_count[i]])

        # count_df.loc[i, 'detector_positive']=len(sorted.channel_name[range(i,len(count_df))])


        if count_df.loc[i, 'channel_name'] in SOZ_channels:
            count_df.loc[i, 'soz_info'] = "SOZ"
            count_df.loc[i, 'doctor'] = 1

        elif count_df.loc[
            i, 'channel_name'] in IZ_channels:  # ll_reviewed_data.loc[i,'onset_channel'] == 'IrritativeZone': #nevypisuje se
            count_df.loc[i, 'soz_info'] = "IrritativeZone"
            count_df.loc[i, 'doctor'] = 1

        else:
            count_df.loc[i, 'soz_info'] = "NON_SOZ"
            count_df.loc[i, 'doctor'] = 0


    count_df = count_df.loc[:,['channel_name','soz_info','total_count','doctor']]


    print 'Creating sorted table "sorted" with %s' %list(sorted.columns.values)
    sorted_df = count_df.sort_values('total_count', ascending=0)

    #--update index after sorting dataframe
    sorted_df=sorted_df.reset_index(drop=True)


    # ------ výpočet FP, FN, TP, TN
    TheDataFrame = pd.DataFrame(0, index=np.arange(len(count_df)), columns=['FP', 'FN', 'TP', 'TN', 'FPR', 'TPR'])

    thresholding_df = pd.DataFrame()

    thresholding_df['channel_name'] = sorted_df.channel_name
    #s['detector'] = count_df.doctor
    thresholding_df.loc[range(0, len(sorted_df)), 'detector'] = 0  # později dát mimo cyklus
    thresholding_df['doctor'] = sorted_df.doctor

    #update index after sorting dataframe
    thresholding_df=thresholding_df.reset_index(drop=True)

    for table_i in range(0, len(sorted_df)):  # count_df.soz_info)):

        for i in range(0, len(sorted_df)):

            # print(str(s.loc[i,'detector']))
            # print(str(s.loc[i,'doctor']))

            a = int(thresholding_df.loc[i, 'detector'])
            b = int(thresholding_df.loc[i, 'doctor'])

            if a == 1 and b == 1:
                to_increment = 'TP'

            elif a == 1 and b == 0:  # s.loc[i,'detector']==1 and s.loc[i,'doctor']==0:
                to_increment = 'FP'

            elif a == 0 and b == 1:  # s.loc[i,'detector']==0 and s.loc[i,'doctor']==1:
                to_increment = 'FN'

            elif thresholding_df.loc[i, 'detector'] == 0 and thresholding_df.loc[i, 'doctor'] == 0:
                to_increment = 'TN'

            TheDataFrame.loc[table_i, to_increment] += 1

            thresholding_df.set_value(table_i, 'detector', 1)

    #TheDataFrame

    # výpočet FPR a TPR, zápis do TheDataFrame

    for i in range(0, len(TheDataFrame)):

        if TheDataFrame.loc[i, 'FP'] != 0:
            TheDataFrame.loc[i, 'FPR'] = float(TheDataFrame.loc[i, 'FP']) / (float(TheDataFrame.loc[i, 'FP']) + float(TheDataFrame.loc[i, 'TN']))
        else:
            TheDataFrame.loc[i, 'FPR'] = 0

        if TheDataFrame.loc[i, 'TP'] != 0:
            TheDataFrame.loc[i, 'TPR'] = float(TheDataFrame.loc[i, 'TP']) / (float(TheDataFrame.loc[i, 'TP']) + float(TheDataFrame.loc[i, 'FN']))
        else:
            TheDataFrame.loc[i, 'TPR'] = 0

    fpr = np.array(TheDataFrame['FPR'])
    tpr = np.array(TheDataFrame['TPR'])

    total_count = sorted_df.total_count
    doctor = sorted_df.doctor

    return (TheDataFrame['FPR'], TheDataFrame['TPR'], total_count, doctor)


def roc_resected(database, seeg, i, columns):
    # --- načtení DataFrame z MySQL workbench
    ll_df = get_data(database, seeg, i, columns)

    # --- funkce pro součet detekcí v jednotlivých kanálech
    count_df = count_hfo_events(ll_df)

    # SELECT * FROM reviewed_events.seizures;
    ll_reviewed_data = get_reviewed_data_resected(seeg)

    count_df['soz_info'] = ''
    count_df['total_count'] = ''

    # count_df['doctor']=99

    resected_channels = list(ll_reviewed_data.loc[(ll_reviewed_data.resection_image == 1), "channel_name"])
    non_resected_channels = list(ll_reviewed_data.loc[(ll_reviewed_data.resection_image == 0), "channel_name"])

    # vytvoření tabulky s počty HFO events
    # print 'Creating table "count_df" with %s' %list(count_df.columns.values)

    for i in range(0, len(count_df)):  # count_df.soz_info)):

        count_df.loc[i, 'total_count'] = sum([count_df.SOZ_count[i], count_df.IZ_count[i], count_df.NON_SOZ_count[i]])

        # count_df.loc[i, 'detector_positive']=len(sorted.channel_name[range(i,len(count_df))])


        if count_df.loc[i, 'channel_name'] in resected_channels:
            # count_df.loc[i, 'soz_info'] = "SOZ"
            count_df.loc[i, 'resected'] = 1
            count_df.loc[i, 'SOZ_count'] = count_df.loc[i, 'total_count']
            count_df.loc[i, 'NON_SOZ_count'] = 0
            count_df.loc[i, 'IZ_count'] = 0


        # elif count_df.loc[
        #     i, 'channel_name'] in IZ_channels:  # ll_reviewed_data.loc[i,'onset_channel'] == 'IrritativeZone': #nevypisuje se
        #     count_df.loc[i, 'soz_info'] = "IrritativeZone"
        #     count_df.loc[i, 'resected'] = 1

        else:
            # count_df.loc[i, 'soz_info'] = "NON_SOZ"
            count_df.loc[i, 'resected'] = 0
            count_df.loc[i, 'NON_SOZ_count'] = count_df.loc[i, 'total_count']
            count_df.loc[i, 'SOZ_count'] = 0
            count_df.loc[i, 'IZ_count'] = 0

    # del count_df.IZ_count
    # ---------přiřadit hodnoty tak, aby když resected = 1

    count_df_soz_info = count_df

    # POZDEJI vyohodit nepotrebne sloupecky
    count_df = count_df.loc[:,['channel_name','soz_info','total_count','resected']]

    # count_df[count_df.soz_info=="IrritativeZone"]

    #print 'Creating sorted table "sorted" with %s' %list(sorted.columns.values)

    sorted_df = count_df.sort_values('total_count', ascending=0)

    #update index after sorting dataframe
    sorted_df=sorted_df.reset_index(drop=True)


    # ------ výpočet FP, FN, TP, TN
    TheDataFrame = pd.DataFrame(0, index=np.arange(len(count_df)), columns=['FP', 'FN', 'TP', 'TN', 'FPR', 'TPR'])

    thresholding_df = pd.DataFrame()

    thresholding_df['channel_name'] = sorted_df.channel_name
    #s['detector'] = count_df.doctor
    thresholding_df.loc[range(0, len(sorted_df)), 'detector'] = 0  # později dát mimo cyklus
    thresholding_df['resected'] = sorted_df.resected

    #update index after sorting dataframe
    thresholding_df=thresholding_df.reset_index(drop=True)


    for table_i in range(0, len(sorted_df)):  # count_df.soz_info)):

        for i in range(0, len(sorted_df)):

            # print(str(s.loc[i,'detector']))
            # print(str(s.loc[i,'doctor']))

            a = int(thresholding_df.loc[i, 'detector'])
            b = int(thresholding_df.loc[i, 'resected'])

            if a == 1 and b == 1:
                to_increment = 'TP'

            elif a == 1 and b == 0:  # s.loc[i,'detector']==1 and s.loc[i,'doctor']==0:
                to_increment = 'FP'

            elif a == 0 and b == 1:  # s.loc[i,'detector']==0 and s.loc[i,'doctor']==1:
                to_increment = 'FN'

            elif thresholding_df.loc[i, 'detector'] == 0 and thresholding_df.loc[i, 'resected'] == 0:
                to_increment = 'TN'

            TheDataFrame.loc[table_i, to_increment] += 1

            thresholding_df.set_value(table_i, 'detector', 1)

    #TheDataFrame

    # výpočet FPR a TPR, zápis do TheDataFrame

    for i in range(0, len(TheDataFrame)):

        if TheDataFrame.loc[i, 'FP'] != 0:
            TheDataFrame.loc[i, 'FPR'] = float(TheDataFrame.loc[i, 'FP']) / (float(TheDataFrame.loc[i, 'FP']) + float(TheDataFrame.loc[i, 'TN']))
        else:
            TheDataFrame.loc[i, 'FPR'] = 0

        if TheDataFrame.loc[i, 'TP'] != 0:
            TheDataFrame.loc[i, 'TPR'] = float(TheDataFrame.loc[i, 'TP']) / (float(TheDataFrame.loc[i, 'TP']) + float(TheDataFrame.loc[i, 'FN']))
        else:
            TheDataFrame.loc[i, 'TPR'] = 0

    fpr = np.array(TheDataFrame['FPR'])
    tpr = np.array(TheDataFrame['TPR'])

    total_count = sorted_df.total_count
    resected = sorted_df.resected

    return (TheDataFrame['FPR'], TheDataFrame['TPR'], total_count, resected, count_df_soz_info)