from flask import Blueprint, render_template, redirect, request, url_for
from flask_login import (
    current_user,
    LoginManager,
    login_required,
    login_user,
    logout_user
)
from .forms import LoginForm, CreateAccountForm
from flask import jsonify, render_template, request, json

# start the login system
login_manager = LoginManager()

blueprint = Blueprint(
    'base_blueprint',
    __name__,
    url_prefix='',
    template_folder='templates',
    static_folder='static'
)

from database import db
from .models import User

import numpy as np
import pandas as pd

sg_table_data = []

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']


def correcting_year_datetime(string_timestamp):
    timestamp = [datetime.strptime(date, '%Y-%m-%d').date() for date in string_timestamp]

    new_dates_list = []
    for item in timestamp:
        month = '{:%m}'.format(item)
        day = '{:%d}'.format(item)
        year = '{:%Y}'.format(item)
        dates = date(int(year)-1, int(month), int(day))
        new_dates_list.append(dates)
    return new_dates_list


import os, sys


# directory =  "/home/cowboyuniverse/Workspace/LearningJournal/SeniorDesign/github/Proj/Insight_Engine/csv/original-csv-files/"
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"): 
#         print(os.path.join(directory, filename))

        patient_id = filename.split('.')[0]
#         print(patient_id)
        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_list= csv_df.sum()
        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']
df_new

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'].mean()
duration = mean_df['Duration'].mean()
max_cardio = mean_df['max_Cardio'].mean()
min_fatBurn = mean_df['Minutes_FatBurn'].mean()
sg = mean_df['Sensor_Glucose'].mean()


labels = [
    'JAN', 'FEB', 'MAR', 'APR',
    'MAY', 'JUN', 'JUL', 'AUG',
    'SEP', 'OCT', 'NOV', 'DEC'
]

values = [
    967.67, 1190.89, 1079.75, 1349.19,
    2328.91, 2504.28, 2873.83, 4764.87,
    4349.29, 6458.30, 9907, 16297
]

colors = [
    "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
    "#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
    "#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]




from random import sample

@blueprint.route('/data')
def data():
    return jsonify({'results': sample(range(1, 10), 5)})


@blueprint.route('/')
def route_default():
	return redirect(url_for('base_blueprint.login'))


@blueprint.route('/<template>')
@login_required
def route_template(template):
	global sg_table_data
	return render_template(template + '.html', sg_table_data=sg_table_data)

@blueprint.route('/fixed_<template>')
@login_required
def route_fixed_template(template):
    return render_template('fixed/fixed_{}.html'.format(template))


@blueprint.route('/page_<error>')
def route_errors(error):
    return render_template('errors/page_{}.html'.format(error))

## Login & Registration


@blueprint.route('/login', methods=['GET', 'POST'])
def login():
    login_form = LoginForm(request.form)
    create_account_form = CreateAccountForm(request.form)
    if 'login' in request.form:
        username = str(request.form['username'])
        password = str(request.form['password'])
        user = db.session.query(User).filter_by(username=username).first()
        if user and password == user.password:
            login_user(user)
            return redirect(url_for('base_blueprint.route_default'))
        return render_template('errors/page_403.html')
    elif 'create_account' in request.form:
        login_form = LoginForm(request.form)
        user = User(**request.form)
        db.session.add(user)
        db.session.commit()
        return redirect(url_for('base_blueprint.login'))
    if not current_user.is_authenticated:
        return render_template(
            'login/login.html',
            login_form=login_form,
            create_account_form=create_account_form
        )
    return redirect(url_for('home_blueprint.index'))


@blueprint.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('base_blueprint.login'))


@blueprint.route('/shutdown')
def shutdown():
    func = request.environ.get('werkzeug.server.shutdown')
    if func is None:
        raise RuntimeError('Not running with the Werkzeug Server')
    func()
    return 'Server shutting down...'

## Errors


@login_manager.unauthorized_handler
def unauthorized_handler():
    return render_template('errors/page_403.html'), 403


@blueprint.errorhandler(403)
def access_forbidden(error):
    return render_template('errors/page_403.html'), 403


@blueprint.errorhandler(404)
def not_found_error(error):
    return render_template('errors/page_404.html'), 404


@blueprint.errorhandler(500)
def internal_error(error):
    return render_template('errors/page_500.html'), 500

