from flask import Blueprint, render_template, request
from flask_login import login_required
from os.path import abspath, dirname, join, pardir
import numpy as np
import pandas as pd
import os, sys
from cassandra.cluster import Cluster

blueprint = Blueprint(
    'home_blueprint',
    __name__,
    url_prefix='/home',
    template_folder='templates',
    static_folder='static'
)

######################## SG STREAM ###############################
sg_table_data = []
######################## END SG STREAM ###########################

######################## RADAR PLOT ##############################
cols = ['Date', 'Sensor_Glucose','Bolus','BG-Calib','Heart-Rate', 'Metabolic','Calories-Out', 'Step-Count',\
        'CalOut_OutOfRange','CalOut_FatBurn','CalOut_Cardio','CalOut_Peak','Minutes_OutOfRange','Minutes_FatBurn',\
        'Minutes_Cardio','Minutes_Peak','max_OutOfRange','max_FatBurn','max_Cardio','max_Peak','min_OutOfRange',\
        'min_FatBurn','min_Cardio','min_Peak','ActivDist_Total','tracker','loggedActivities','veryActive','moderatelyActive',\
        'lightlyActivity','sedentaryActive',\
        'AwakeCount', 'AwakeDuration', 'AwakeningsCount', 'Duration','Efficiency',\
        'IsMainSleep', 'MinutesAfterWakeUp', 'MinutesAsleep','MinutesAwake',\
        'MinutesToFallAsleep', 'RestlessCount','RestlessDuration', 'TimeInBed',\
        'BMI', 'Weight','Fat']



directory = "/home/medtronic/CSV_DATA/all_patient_daily_avg_total_df/"
total_df = pd.DataFrame()
mean_df = pd.DataFrame()

for filename in os.listdir(directory):
    if filename.endswith(".csv"): 
        patient_id = filename.split('.')[0]
        csv_df = pd.read_csv(os.path.join(directory, filename))
        csv_df = csv_df.drop('Unnamed: 0', 1)
        csv_df['Patient_id'] = patient_id
        mean_list = csv_df.mean()

        total_df = total_df.append(csv_df)
        mean_one_patient = pd.DataFrame()
        mean_one_patient= mean_list.to_frame(name=None)
        mean_one_patient = mean_one_patient.transpose()
        mean_one_patient['Patient_id'] = patient_id
        mean_df = mean_df.append(mean_one_patient) 

    else:
        continue
		
df_new = pd.DataFrame()
df_new = mean_df.loc[mean_df['Patient_id'] == '1']


new_weight = df_new['Weight'].mean()
new_duration = df_new['Duration'].mean()
new_max_cardio = df_new['max_Cardio'].mean()
new_min_fatBurn = df_new['Minutes_FatBurn'].mean()
new_sg = df_new['Sensor_Glucose'].mean()

weight = mean_df['Weight'].iloc[0]
duration = mean_df['Duration'].mean()
max_cardio = mean_df['max_Cardio'].mean()
min_fatBurn = mean_df['Minutes_FatBurn'].mean()
sg_mean = mean_df['Sensor_Glucose'].mean()



new_fiber= df_new['fiber'].mean()
new_lipids = df_new['lipids'].mean()
new_sugars= df_new['sugars'].mean()
new_Carb = df_new['Carb'].mean()
new_Saturatedfattyacids= df_new['Saturatedfattyacids'].mean()

fiber = mean_df['fiber'].mean()
lipids = mean_df['lipids'].mean()
sugars = mean_df['sugars'].mean()
Carb = mean_df['Carb'].mean()
Saturatedfattyacids = mean_df['Saturatedfattyacids'].mean()
###################### END RADAR PLOT ############################



@blueprint.route('/index')
@login_required
def index():
    radar_labels=['Weight','Duration','max_Cardio','Minutes_FatBurn','Sensor_Glucose']
    radar_value1=[new_weight,new_duration ,new_max_cardio,new_min_fatBurn,new_sg]
    radar_value2=[weight,duration ,max_cardio,min_fatBurn,sg_mean]
    radar2_value1=[new_fiber,new_lipids ,new_sugars,new_Carb,new_Saturatedfattyacids]
    radar2_value2=[fiber,lipids ,sugars,Carb,Saturatedfattyacids]
    rowsresults = getData0("")
    rows_array = []
    for i in rowsresults:
        print(i.insight)
        rows_array.append(str(i.insight))
    return render_template('index.html', sg_table_data=sg_table_data, radar2_value1=radar2_value1, radar2_value2=radar2_value2,radar_value1=radar_value1, radar_value2=radar_value2, radar_labels=radar_labels, insights=rows_array)


@blueprint.route('/<template>')
@login_required
def route_template(template):
    return render_template(template + '.html')
	
@blueprint.route('/sg', methods=['POST'])
def sg():
	json = request.get_json()
	print(str((json['time'] - 719529.0)*86400000) + ', ' + str(json['dataValue']))
	#print(json)
	global sg_table_data
	sg_table_data.append([(json['time'] - 719529.0)*86400000, json['dataValue']])
	while len(sg_table_data) >= 25:
		sg_table_data.remove(sg_table_data[0])
	#print (sg_table_data)
	return ''#sg_table_data


########################### GETTING INSIGHTS FROM CASSANDRA DB ######################

DB0Address = "198.27.98.46"
DB0Keyspace = "insightdb"
DB1Address = ""
DB1Address = ""

def getData0(inputPatient): #input requires patient ID, metric ID, metric GROUP, TS
    inputPatient = "1"
    inputMetricID = "sg"
    inputMetricGroup = "CGMData"
    inputTS = 736902.0

    queryTSRange =  "SELECT * from insight_data WHERE patient_id = {} limit 5;".format(inputPatient)

#     print(queryTSRange)
    cluster = Cluster([DB0Address])
    session = cluster.connect(DB0Keyspace)

    rows = session.execute(queryTSRange)

    return rows


### END GETTING INSIGHTS ###