from flask import Flask, flash, request, redirect, url_for, render_template
import urllib.request
from werkzeug.utils import secure_filename
from fileinput import filename
import pandas as pd
import numpy as np
import os
import glob
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt


def read_all_csv(path='./rawdata_csv/', extension='csv'):
    result = glob.glob(path+'SRC_R*.{}'.format(extension))
    df=None
    for file in result:
        if(df is None):
            df=pd.read_csv(file)
        else:
            df=pd.concat([df,pd.read_csv(file)], ignore_index=True)
    df_master=pd.read_csv("SRC_MasterData.csv")
    df_master=df_master[['State_Code','State_Name','Total_Population']]
    final_df = pd.merge(df, df_master, on='State_Code', how='inner')
    final_df['total']=final_df[['Primary_Only','Primary_with_Upper_Primary','Primary with_Upper_Primary_Sec_H.Sec','Upper_Primary_Only','Upper_Primary_with_Sec_H.Sec','Primary_with_Upper_Primary_Sec','Upper_Primary_with _Sec']].sum(axis=1)
    final_df['total_by_pop']=final_df['total']/final_df['Total_Population']

    final_df=final_df[["Year","State_Name","State_Code","Main_Dimension","Sub_Dimension","Total_Population",'total','total_by_pop']]

    return final_df

final_df=read_all_csv()

app = Flask(__name__)
 
UPLOAD_FOLDER = 'static/'
 
app.secret_key = "secret key"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config["CACHE_TYPE"] = "null"
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0

# app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
 
# ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
 
# def allowed_file(filename):
#     return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def prepare_graph(filename):
    data=list(np.random.uniform(1, 10, size=(10,1)).reshape(-1))
    ind = np.arange(len(data))
#     plt.ioff()
    fig = plt.figure(figsize=(8,6))
    plt.plot(data, label='Number of Schools', ls='--', color='black', marker='o', markersize=9, mew=2, linewidth=2)
    plt.xlabel('Year')
    plt.ylabel('Number of Schools')
    plt.xticks(ind, [2000+i for i in ind])
    plt.legend(loc=0)
    plt.savefig('./static/'+filename)
    plt.close(fig)

@app.after_request
def add_header(request):
    """
    Add headers to both force latest IE rendering engine or Chrome Frame,
    and also to cache the rendered page for 10 minutes.
    """
    request.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    request.headers["Pragma"] = "no-cache"
    request.headers["Expires"] = "0"
    request.headers['Cache-Control'] = 'public, max-age=0'
    return request
    
@app.route('/')
def home():
    return render_template('index.html')

@app.route('/index.html')
def index():
    return render_template('index.html')

@app.route('/students.html')
def students():
    return render_template('students.html')

@app.route('/teachers.html')
def teachers():
    return render_template('teachers.html')

@app.route('/schools.html')
def schools():
    return render_template('schools.html')

@app.route('/classrooms.html')
def classrooms():
    return render_template('classrooms.html')

@app.route('/facilities.html')
def facilities():
    return render_template('facilities.html')

# display selected image
@app.route('/get_card_from_index', methods=['POST'])
def get_card_from_index():    
    card_from_index = 'img/sample_trend_schools.jpeg'
    prepare_graph(card_from_index)
    return render_template('index.html', card_from_index=card_from_index)

@app.route('/get_facilities_from_index', methods=['POST'])
def get_facilities_from_index():    
    facilities_from_index = 'img/sample_trend_facilities.jpeg'
    prepare_graph(facilities_from_index)
    return render_template('index.html', facilities_from_index=facilities_from_index)

@app.route('/get_trend_from_students', methods=['POST'])
def get_trend_from_students():
    trend_from_students = 'img/sample_trend_students_new.jpeg'
    prepare_graph(trend_from_students)
    return render_template('students.html', trend_from_students=trend_from_students)

@app.route('/get_distribution_from_students', methods=['POST'])
def get_distribution_from_students():
    distribution_from_students = 'img/sample_distribution_students_new.jpeg'
    prepare_graph(distribution_from_students)
    return render_template('students.html', distribution_from_students=distribution_from_students)

@app.route('/get_trend_from_teachers', methods=['POST'])
def get_trend_from_teachers():
    trend_from_teachers = 'img/sample_trend_teachers_new.jpeg'
    prepare_graph(trend_from_teachers)
    return render_template('teachers.html', trend_from_teachers=trend_from_teachers)

@app.route('/get_distribution_from_teachers', methods=['POST'])
def get_distribution_from_teachers():
    distribution_from_teachers = 'img/sample_distribution_teachers_new.jpeg'
    prepare_graph(distribution_from_teachers)
    return render_template('teachers.html', distribution_from_teachers=distribution_from_teachers)

@app.route('/get_trend_from_schools', methods=['POST'])
def get_trend_from_schools():
    trend_from_schools = 'img/sample_trend_schools_new.jpeg'
    prepare_graph(trend_from_schools)
    return render_template('schools.html', trend_from_schools=trend_from_schools)

@app.route('/get_distribution_from_schools', methods=['POST'])
def get_distribution_from_schools():
    distribution_from_schools = 'img/sample_distribution_schools_new.jpeg'
    prepare_graph(distribution_from_schools)
    return render_template('schools.html', distribution_from_schools=distribution_from_schools)

@app.route('/get_trend_from_classrooms', methods=['POST'])
def get_trend_from_classrooms():
    trend_from_classrooms = 'img/sample_trend_classrooms_new.jpeg'
    prepare_graph(trend_from_classrooms)
    return render_template('classrooms.html', trend_from_classrooms=trend_from_classrooms)

@app.route('/get_distribution_from_classrooms', methods=['POST'])
def get_distribution_from_classrooms():
    distribution_from_classrooms = 'img/sample_distribution_classrooms_new.jpeg'
    prepare_graph(distribution_from_classrooms)
    return render_template('classrooms.html', distribution_from_classrooms=distribution_from_classrooms)

@app.route('/get_trend_from_facilities', methods=['POST'])
def get_trend_from_facilities():
    trend_from_facilities = 'img/sample_trend_facilities_new.jpeg'
    prepare_graph(trend_from_facilities)
    return render_template('facilities.html', trend_from_facilities=trend_from_facilities)

@app.route('/get_distribution_from_facilities', methods=['POST'])
def get_distribution_from_facilities():
    distribution_from_facilities = 'img/sample_distribution_facilities_new.jpeg'
    prepare_graph(distribution_from_facilities)
    return render_template('facilities.html', distribution_from_facilities=distribution_from_facilities)

# submit image and display
# @app.route('/', methods=['POST'])
# def upload_image():
#     print(request.files)
#     if 'file' not in request.files:
#         flash('No file part')
#         return redirect(request.url)
#     file = request.files['file']
#     if file.filename == '':
#         flash('No image selected for uploading')
#         return redirect(request.url)
#     if file and allowed_file(file.filename):
#         filename = secure_filename(file.filename)
#         file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
#         print('upload_image filename: ' + filename)
#         flash('Image successfully uploaded and displayed below')
#         return render_template('index.html', filename=filename)
#     else:
#         flash('Allowed image types are - png, jpg, jpeg, gif')
# #         print(request.url)
#         return redirect(request.url)

# # @app.route('/display/<filename>')
# @app.route('/display/<filename>')
# def display_image(filename):
#     pass
# #     print('display_image filename: ' + filename)
#     return redirect(url_for('static', filename=filename), code=301)


if __name__ == "__main__":
    app.run()