# For setting up server and html files
from flask import Flask, render_template
# For unpacking data coming from Anxiety Assessment
import json
# For plotting the data on radar charts
import matplotlib.pyplot as plt
# For manipulating data
import numpy as np
# For handling file checks and statistical analysis
import os,sys,math

# TODO: Figure out how to not show deleted records charts.
# Problem has to do with not updating responses csv when a record is deleted since it only updates on submit.


app = Flask(__name__)

keys = ['LHA', 'RHA', 'IA', 'AA', 'OA', 'EoUA', 'RPR', 'UAFoB', 'LoCoytoa', 'ER']
full_names = ["Left Hemisphere Anxiety","Right Hemisphere Anxiety","Interpretation Anxiety","Anticipation Anxiety","Obsession Anxiety","Experience of Unexplained Anxiety",
    "Rapid Physiological Responding","Unplanned Aggressive Feelings or Behavior","Loss of Control of Your Thoughts or Actions","Extreme Responses"]
@app.route('/')
def index():
    global full_names,keys
    debug = []
    project_dir = os.path.dirname(__file__)
    input_file = open(f"{project_dir}/form_response.csv","r")
    data = json.load(input_file)
    input_file.close()
    data_len = len(data)
    for i,record in enumerate(data):
        i+=1
        print(list(record.values()))
        if not os.path.exists(f"{project_dir}/static/record{i}.png"):
            print("Generate Chart")
            generateChart(i,list(record.values()))
        else:
            print("Chart Exists")
    return render_template('index.html',data=data,full_names=full_names)

@app.route("/collage")
def collage():
    global full_names
    project_dir = os.path.dirname(__file__)
    input_file = open(f"{project_dir}/form_response.csv","r")
    data = json.load(input_file)
    return render_template('collage.html',data=data,full_names=full_names,keys=keys)


def generateChart(index,record):
    global full_names,keys
    project_dir = os.path.dirname(__file__)
    # We are expecting each record to have 10 values
    # Calculate the angles for each axis of the chart
    angles = np.linspace(0,2*np.pi, len(record), endpoint = False)

    record.append(record[0])
    angles = np.concatenate((angles,[angles[0]]))

    fig = plt.figure(figsize=(6,6),dpi=300)
    ax = fig.add_subplot(111,polar=True)

    ax.plot(angles,record,'o-', linewidth=2)

    ax.fill(angles, record, alpha=0.25)
    
    ax.set_rlabel_position(2)
    ax.set_ylim(0,8)
    ax.set_yticks([2,4,6,8])
    ax.set_yticklabels(["2","4","6","8"], fontsize=10)

    ax.set_xticks(angles[:-1])
    ax.set_xticklabels(keys,fontsize=12)

    print(f"Record {index}")
    ax.set_title(f"Record {index}", fontsize=26, y=1.05)
    plt.savefig(f"{project_dir}/static/record{index}")



def calculateStats(data):
    all_stats = []
    # All averages for each anxiety type
    for i,record in enumerate(data):
        avg = math 
    pass
def test():
    global full_names,keys
    debug = []
    input_file = open("form_response.csv","r")
    data = json.load(input_file)
    data_len = len(data)
    print(data_len)
    file_exists = os.path.exists("static/record1.png")
    print(file_exists)
    for i,record in enumerate(data):
        i+=1
        print(list(record.values()))
        if not os.path.exists(f"static/record{i}.png"):
            print("Generate Chart")
            generateChart(i,list(record.values()))
        else:
            print("Chart Exists")


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5002, debug=True)
