#----------------------------------------------------------------------------#
# Imports
#----------------------------------------------------------------------------#

from flask import Flask, render_template, request, redirect
# from flask_sqlalchemy import SQLAlchemy
import logging
from logging import Formatter, FileHandler
from forms import *
import os
from match import match, compare
from student import student
from course import course

import sqlite3
from flask import g
from helpers import *

#----------------------------------------------------------------------------#
# App Config.
#----------------------------------------------------------------------------#

app = Flask(__name__)
app.config.from_object('config')
# app.config ["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///class.sqlite3'
#db = SQLAlchemy(app)
DATABASE = "C:\\Users\\bishw\\GIT_shell\\flask-boilerplate\\database.db"


def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        db = g._database = sqlite3.connect(DATABASE)
        db.row_factory = sqlite3.Row
    return db


@app.teardown_appcontext
def close_connection(exception):
    db = getattr(g, '_database', None)
    if db is not None:
        db.close()


#----------------------------------------------------------------------------#
# Controllers.
#----------------------------------------------------------------------------#


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


@app.route('/database')
def database():
    # opens db
    db = get_db()
    crsr = db.cursor()
    # GET ALL USERS
    users = crsr.execute("SELECT * FROM users;").fetchall()
    # print(rowput(users))
    # GET ALL PROFILES
    profiles = crsr.execute("SELECT * FROM profiles;").fetchall()
    # print(rowput(profiles))
    classes = crsr.execute(
        "SELECT * FROM classes ORDER BY fkey_user ASC;").fetchall()
    classes = parseClasses(rowput(classes), rowput(users))
    # print(classes)
    return render_template('/pages/database.html', users=rowput(users), profiles=transformData(rowput(profiles)), classes=classes)


@app.route('/create_profile', methods=["GET", "POST"])
def profile():
    if request.method == "POST":
        name = request.form['name']
        major = request.form['major']
        year = request.form['year']
        dorm_apartment = request.form["dorm/apartment"]
        school = request.form["school"]
        interests = request.form["interests"]

        # fill courses array with form input
        courses = []
        for i in range(5):
            course_name = request.form['course_' + str(i + 1)]
            professor = request.form['professor_' + str(i + 1)]

            if course_name != "" and professor != "":
                selected_course = course(course_name, professor)
                courses.append(selected_course)

        # fill study methods array with form input
        study = []
        for i in range(3):
            study_method = request.form['study_method_' + str(i + 1)]
            study.append(study_method)

        curr_user = student(name, major, year,
                            dorm_apartment, courses, study, interests)

        db = get_db()
        crsr = db.cursor()
        users = rowput(crsr.execute("SELECT * FROM users;").fetchall())
        profiles = transformData(
            rowput(crsr.execute("SELECT * FROM profiles;").fetchall()))
        classes = crsr.execute(
            "SELECT * FROM classes ORDER BY fkey_user ASC;").fetchall()
        classes_raw = classes
        classes = parseClasses(rowput(classes), rowput(users))

        courses = []
        courses_names = set()
        students = []

        for i in range(len(users)):

            separate_courses = classes[i + 1].strip().split("; ")
            separate_courses = [c.strip() for c in separate_courses]
            courses_arr = []

            for c in separate_courses:
                course_split = c.split(" with ")
                f = filter(str.isalpha, course_split[1])
                course_split[1] = "".join(f)
                course_name = course_split[0]
                course_professor = course_split[1]
                print(course_split)
                print("-----")

                courses_arr.append(course(course_name, course_professor))

            students.append(student(users[i]["name"], profiles[i]["major"], profiles[i]["year"],
                                    "Rawlings", courses_arr, profiles[i]["study"], profiles[i]["interests"]))
        for i in range(len(classes_raw)):
            tempcourse = (classes_raw[i]["class"], classes_raw[i]["professor"])
            courses_names.add(tempcourse)
        for course_info in courses_names:
            courses.append(course(course_info[0], course_info[1]))

        print(students)
        for c in curr_user.courses:
            print(c.name, c.professor)

        print(curr_user.study)
        print("----")
        matches = match(curr_user, students)

        print(matches)

        return render_template("matches.html", matches=matches)
    else:
        return render_template('createprofile.html')


@app.route('/matches')
def matches():

    return render_template('matches.html')


@app.route('/post')
def post():
    return render_template('matches.html')
# Error handlers.


@app.errorhandler(500)
def internal_error(error):
    # db_session.rollback()
    return render_template('errors/500.html'), 500


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


if not app.debug:
    file_handler = FileHandler('error.log')
    file_handler.setFormatter(
        Formatter(
            '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')
    )
    app.logger.setLevel(logging.INFO)
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)
    app.logger.info('errors')

#----------------------------------------------------------------------------#
# Launch.
#----------------------------------------------------------------------------#

# Default port:
if __name__ == '__main__':
    app.run()

# Or specify port manually:
'''
if __name__ == '__main__':
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)
'''

#----------------------------------------------------------------------------#
# Imports
#----------------------------------------------------------------------------#

from flask import Flask, render_template, request, redirect
# from flask_sqlalchemy import SQLAlchemy
import logging
from logging import Formatter, FileHandler
from forms import *
import os
from match import match, compare
from student import student
from course import course

import sqlite3
from flask import g
from helpers import *

#----------------------------------------------------------------------------#
# App Config.
#----------------------------------------------------------------------------#

app = Flask(__name__)
app.config.from_object('config')
# app.config ["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///class.sqlite3'
#db = SQLAlchemy(app)
DATABASE = "C:\\Users\\bishw\\GIT_shell\\flask-boilerplate\\database.db"


def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        db = g._database = sqlite3.connect(DATABASE)
        db.row_factory = sqlite3.Row
    return db


@app.teardown_appcontext
def close_connection(exception):
    db = getattr(g, '_database', None)
    if db is not None:
        db.close()


#----------------------------------------------------------------------------#
# Controllers.
#----------------------------------------------------------------------------#


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


@app.route('/database')
def database():
    # opens db
    db = get_db()
    crsr = db.cursor()
    # GET ALL USERS
    users = crsr.execute("SELECT * FROM users;").fetchall()
    # print(rowput(users))
    # GET ALL PROFILES
    profiles = crsr.execute("SELECT * FROM profiles;").fetchall()
    # print(rowput(profiles))
    classes = crsr.execute(
        "SELECT * FROM classes ORDER BY fkey_user ASC;").fetchall()
    classes = parseClasses(rowput(classes), rowput(users))
    # print(classes)
    return render_template('/pages/database.html', users=rowput(users), profiles=transformData(rowput(profiles)), classes=classes)


@app.route('/create_profile', methods=["GET", "POST"])
def profile():
    if request.method == "POST":
        name = request.form['name']
        major = request.form['major']
        year = request.form['year']
        dorm_apartment = request.form["dorm/apartment"]
        school = request.form["school"]
        interests = request.form["interests"]

        # fill courses array with form input
        courses = []
        for i in range(5):
            course_name = request.form['course_' + str(i + 1)]
            professor = request.form['professor_' + str(i + 1)]

            if course_name != "" and professor != "":
                selected_course = course(course_name, professor)
                courses.append(selected_course)

        # fill study methods array with form input
        study = []
        for i in range(3):
            study_method = request.form['study_method_' + str(i + 1)]
            study.append(study_method)

        curr_user = student(name, major, year,
                            dorm_apartment, courses, study, interests)

        db = get_db()
        crsr = db.cursor()
        users = rowput(crsr.execute("SELECT * FROM users;").fetchall())
        profiles = transformData(
            rowput(crsr.execute("SELECT * FROM profiles;").fetchall()))
        classes = crsr.execute(
            "SELECT * FROM classes ORDER BY fkey_user ASC;").fetchall()
        classes_raw = classes
        classes = parseClasses(rowput(classes), rowput(users))

        courses = []
        courses_names = set()
        students = []

        for i in range(len(users)):

            separate_courses = classes[i + 1].strip().split("; ")
            separate_courses = [c.strip() for c in separate_courses]
            courses_arr = []

            for c in separate_courses:
                course_split = c.split(" with ")
                f = filter(str.isalpha, course_split[1])
                course_split[1] = "".join(f)
                course_name = course_split[0]
                course_professor = course_split[1]
                print(course_split)
                print("-----")

                courses_arr.append(course(course_name, course_professor))

            students.append(student(users[i]["name"], profiles[i]["major"], profiles[i]["year"],
                                    "Rawlings", courses_arr, profiles[i]["study"], profiles[i]["interests"]))
        for i in range(len(classes_raw)):
            tempcourse = (classes_raw[i]["class"], classes_raw[i]["professor"])
            courses_names.add(tempcourse)
        for course_info in courses_names:
            courses.append(course(course_info[0], course_info[1]))

        print(students)
        for c in curr_user.courses:
            print(c.name, c.professor)

        print(curr_user.study)
        print("----")
        matches = match(curr_user, students)

        print(matches)

        return render_template("matches.html", matches=matches)
    else:
        return render_template('createprofile.html')


@app.route('/matches')
def matches():

    return render_template('matches.html')


@app.route('/post')
def post():
    return render_template('matches.html')
# Error handlers.


@app.errorhandler(500)
def internal_error(error):
    # db_session.rollback()
    return render_template('errors/500.html'), 500


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


if not app.debug:
    file_handler = FileHandler('error.log')
    file_handler.setFormatter(
        Formatter(
            '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')
    )
    app.logger.setLevel(logging.INFO)
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)
    app.logger.info('errors')

#----------------------------------------------------------------------------#
# Launch.
#----------------------------------------------------------------------------#

# Default port:
if __name__ == '__main__':
    app.run()

# Or specify port manually:
'''
if __name__ == '__main__':
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)
'''

#----------------------------------------------------------------------------# # Imports #----------------------------------------------------------------------------# # from flask_sqlalchemy import SQLAlchemy #----------------------------------------------------------------------------# # App Config. #----------------------------------------------------------------------------# # app.config ["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///class.sqlite3' #db = SQLAlchemy(app) #----------------------------------------------------------------------------# # Controllers. #----------------------------------------------------------------------------# # opens db # GET ALL USERS # print(rowput(users)) # GET ALL PROFILES # print(rowput(profiles)) # print(classes) # fill courses array with form input # fill study methods array with form input # Error handlers. # db_session.rollback() # @app.errorhandler(404) # def not_found_error(error): #  return render_template('errors/404.html'), 404 #----------------------------------------------------------------------------# # Launch. #----------------------------------------------------------------------------# # Default port: # Or specify port manually: if __name__ == '__main__':     port = int(os.environ.get('PORT', 5000))     app.run(host='0.0.0.0', port=port)