from minni.lib.authentication import Authentication
from minni.lib.record import Record
from minni.lib.person import Person

from flask import Flask, Blueprint, request, render_template, redirect, url_for, redirect, current_app, send_from_directory

bp = Blueprint('minni_web', __name__)

def before_all():
    if not Authentication.is_authenticated() and not request.path == "/login":
        return redirect(url_for("minni_web.getLogin"))

bp.before_request(before_all)

@bp.route("/logout", methods=["GET"])
def logout():
    Authentication.destroy_session()
    return redirect(url_for("minni_web.getLogin"))

@bp.route("/login", methods=['GET'])
def getLogin():
    return render_template("login.html")

@bp.route("/login", methods=['POST'])
def postLogin():
    if Authentication.create_session(request.form):
        return redirect(url_for("minni_web.home"))
    else:
        return render_template("login.html", error="Incorrect username or password.")


@bp.route("/")
def home():
    records = Record.fetch_all()
    return render_template("home.html", data=records)

@bp.route("/new_record", methods=["GET"])
def new_record():
    return render_template("new_record.html")

@bp.route("/record", methods=['POST'])
def add_record():
    Record.create(request.form)
    return redirect(url_for("minni_web.home"))

@bp.route("/record/<rowid>", methods=["GET"])
def get_edit_record(rowid):
    record = Record.fetch(rowid)
    return render_template("record.html", data=record)


@bp.route("/record/<rowid>", methods=["POST"])
def post_edit_record(rowid):
    Record.update(rowid, request.form)
    return redirect(url_for("minni_web.home"))

@bp.route("/record/<rowid>/delete", methods=["GET"])
def delete_record(rowid):
    if not Authentication.is_authenticated():
        return redirect(url_for("minni_web.getLogin"))

    Record.delete(rowid)
    return redirect(url_for("minni_web.home"))

@bp.errorhandler(404)
def page_not_found(error):
    return "Page not found"

@bp.errorhandler(500)
def server_error(error):
    return "Page error"
