# -*- coding: utf-8 -*-

from flask import Flask, jsonify, session, abort
from flask import render_template, request, redirect, url_for
from flask_login import LoginManager, current_user, login_user, logout_user, login_required

import datetime
import hashlib
from database.models import Ockovani, PravidelnaProhlidka, Objednavka, db, User, Pacient, Liek, Navsteva, RegistrovanyPacient, CudziPacient, Predepsal, Vykon, OdborneVysetrenie, Faktura
from config import CONFIG


app = Flask(__name__)
app.secret_key = CONFIG["secret_key"]
login_manager = LoginManager()
login_manager.init_app(app)
app.config["SQLALCHEMY_DATABASE_URI"] = CONFIG["database"]
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['MYSQL_DATABASE_CHARSET'] = 'utf8mb4'

db.init_app(app)

PERMANENT_SESSION_LIFETIME = datetime.timedelta(minutes=10)


@app.context_processor
def add_session_config():
    """
    Nastavenie platnosti session na 10 min
    """
    return {
        'PERMANENT_SESSION_LIFETIME_MS': (
            app.permanent_session_lifetime.seconds * 1000),
    }


@app.route("/ping", methods=['POST'])
def ping():
    """
    Predĺženie platnosti cookies
    """
    session.modified = True
    return 'OK'


@login_manager.user_loader
def load_user(user_id):
    """
    Spracovavanie cookies
    :param user_id:
    :return:
    """
    return User.query.filter(User.id == user_id).first()


@app.route("/login", methods=["GET", "POST"])
def login():
    """
    Prihlasovanie do rozhrania, nastavenie cookies
    :return:
    """
    if request.method == "POST":
        if request.form.get("username") and request.form.get("password"):
            password = request.form.get("password")
            user = User.query.filter(User.username == request.form.get("username"), User.password == hashlib.md5(password.encode('utf-8')).hexdigest()).first()
            if user:
                login_user(user)
                return redirect(url_for("index"))
            session["message"] = "Nesprávne meno alebo heslo. Prosím skúste to znova."
        else:
            return redirect(url_for("index"))

    return redirect(url_for("index"))


@app.route("/logout", methods=["GET", "POST"])
@login_required
def logout():
    """
    Odhlasenie uzivatela a odstranie cookies
    :return:
    """
    session["message"] = "Užívateľ bol odhlásený z dôvodu neaktivity." if "timeout" in request.args else "Užívateľ bol úspešne odhlásený."
    logout_user()
    return redirect(url_for("index"))


@app.route("/", methods=["GET", "POST"])
def index():
    """
    Domovska stranka projektu. Podla toho ci je uzivatel prihlaseny alebo nie, tak sa zobrazi spravna verzia
    :return:
    """
    message = None
    try:
        message = session["message"]
        session.pop("message", None)
    except KeyError:
        pass

    if current_user.is_authenticated:
        stats = {
            "navstevy": db.session.query(Navsteva).count(),
            "lieky":  db.session.query(Liek).count(),
            "ukony":  db.session.query(Vykon).count(),
            "pacienti":  db.session.query(Pacient).count()
        }
        user_type = current_user.user_type

        objednavky = []
        rano = str(datetime.date.today()) + " 00:00:00"
        vecer = str(datetime.date.today()) + " 23:59:59"
        for i in db.session.query(Objednavka.id_terminu, Objednavka.datum, Pacient.jmeno, Pacient.prijmeni, RegistrovanyPacient.rodne_cislo).join(
                RegistrovanyPacient).join(Pacient).filter(Objednavka.datum >= datetime.datetime.strptime(rano, '%Y-%m-%d %H:%M:%S'))\
                .filter(Objednavka.datum <= datetime.datetime.strptime(vecer, '%Y-%m-%d %H:%M:%S')).all():
            ukon = db.session.query(Vykon).filter(Vykon.id_terminu == int(i[0])).first()
            current = {
                "id_terminu": i[0],
                "datum": str(i[1])[:-3],
                "jmeno": i[2] + " " + i[3],
                "rodne_cislo": i[4],
                "ukon": ukon.nazev,
            }
            objednavky.append(current)

        if current_user.user_type == "A":
            doktori = db.session.query(User).filter(User.user_type == "D")
            sestricky = db.session.query(User).filter(User.user_type == "S")
            return render_template("admin.html", message=message, stats=stats, doktori=doktori, sestricky=sestricky, user_type=user_type, heading="Nástenka")
        elif current_user.user_type == "D":
            return render_template("index.html", message=message, stats=stats, user_type=user_type, heading="Nástenka", objednavky=objednavky)
        elif current_user.user_type == "S":
            return render_template("index.html", message=message, stats=stats, user_type=user_type, heading="Nástenka", objednavky=objednavky)
    else:
        return render_template("index-login.html", message=message)


@app.route("/api/liek", methods=["GET", "POST"])
def change_liek():
    # if current_user.is_authenticated and (current_user.user_type == "S" or current_user.user_type == "D") and request.method == "GET":
    #     if "liek" in request.args and "remove" in request.args:
    #         liek = Liek.query.filter(Liek.id_lieku == request.args["liek"]).first()
    #         if liek:
    #             db.session.delete(liek)
    #             db.session.commit()
    #             session["message"] = "Liek bol úspešne odstránený."
    #             return redirect(url_for("lieky"))
    #         else:
    #             return abort(404)
    #     else:
    #         return abort(404)

    if current_user.is_authenticated and (current_user.user_type == "S" or current_user.user_type == "D"):
        if request.method == "GET" and "id_lieku" in request.args:
            liek = Liek.query.filter(Liek.id_lieku == request.args["id_lieku"]).first()
            if liek:
                return jsonify({
                    "id_lieku": liek.id_lieku,
                    "nazov":    liek.nazov,
                    "balenie":  liek.balenie,
                }), 200
            else:
                return abort(404)
        elif request.method == "POST":
            if request.form.get("id_lieku"):
                liek = Liek.query.filter(Liek.id_lieku == request.form.get("id_lieku")).first()
                if liek:
                    liek.nazov = request.form.get("nazov")
                    liek.balenie = request.form.get("balenie")
                    db.session.add(liek)
                    db.session.commit()
                    session["message"] = "Liek bol úspešne upravený."
                    return redirect(url_for("lieky"))
                else:
                    return abort(404)
            else:
                liek = Liek(nazov=request.form.get("nazov"), balenie=request.form.get("balenie"))
                db.session.add(liek)
                db.session.commit()
                session["message"] = "Liek bol úspešne pridaný do databázy."
                return redirect(url_for("lieky"))
        else:
            abort(404)
    else:
        return abort(404)


@app.route("/api/objednavka/<id_terminu>", methods=["GET"])
def api_objednavka(id_terminu):
    if current_user.is_authenticated and (current_user.user_type == "S" or current_user.user_type == "D"):
        objednavka = db.session.query(Objednavka).filter(Objednavka.id_terminu == int(id_terminu)).first()

        if "delete" in request.args and objednavka:
            ukon = db.session.query(Vykon).filter(Vykon.id_terminu == objednavka.id_terminu).first()
            db.session.delete(objednavka)
            db.session.commit()
            db.session.delete(ukon)
            db.session.commit()
            session["message"] = "Objednávka bola úspešne odstránená."
            return redirect("/objednavky?tabulka", 302)

        if objednavka:
            pacient = db.session.query(Pacient).filter(Pacient.rodne_cislo == int(objednavka.rodne_cislo)).first()
            ukon = db.session.query(Vykon).filter(Vykon.id_terminu == int(id_terminu)).first()
            response = {
                "pacient": pacient.jmeno + " " + pacient.prijmeni + " (" + str(pacient.rodne_cislo) + ")",
                "nazov_ukonu": ukon.nazev,
                "rodne_cislo": pacient.rodne_cislo,
                "datum": objednavka.datum.strftime('%m/%d/%Y'),
                "cas":  objednavka.datum.strftime('%H:%M') + ":00",

            }
            return jsonify(response), 200
        else:
            return abort(404)
    else:
        return abort(404)


@app.route("/api/objednavky", methods=["POST"])
def api_objednavky():
    if current_user.is_authenticated and (current_user.user_type == "S" or current_user.user_type == "D"):
        try:
            if not request.form.get("pacient_id"):
                session["message"] = "Nepodarilo sa pridať objednávku do DB."
                raise
            else:
                pacient = db.session.query(Pacient).filter(Pacient.rodne_cislo == int(request.form.get("pacient_id"))).first()
                if not pacient:
                    session["message"] = "Nepodarilo sa pridať objednávku do DB."
                    raise

            try:
                try:
                    datum = datetime.datetime.strptime(request.form.get("datum") + " " + request.form.get("cas"), '%m/%d/%Y %H:%M:%S')
                except:
                    datum = datetime.datetime.strptime(request.form.get("datum") + " " + request.form.get("cas"), '%Y-%m-%d %H:%M:%S')
            except:
                session["message"] = "Nesprávny formát dátum alebo času..."
                raise
            try:
                print("asasdsd")
                print(request.form.get("id_objednavky"))
                objednavka = db.session.query(Objednavka).filter(Objednavka.id_terminu == int(request.form.get("id_objednavky"))).first()
            except:
                objednavka = None

            if objednavka:
                ukon = db.session.query(Vykon).filter(Vykon.id_terminu == objednavka.id_terminu).first()
                db.session.delete(objednavka)
                db.session.commit()
                db.session.delete(ukon)
                db.session.commit()

            if db.session.query(Objednavka).filter(Objednavka.datum == datum).first():
                session["message"] = "Nepodarilo sa pridať objednávku v tomto termíne už nejaká objednávka je zadaná."
                return redirect(url_for("objednavky"))

            objednavka = Objednavka(datum=datum, rodne_cislo=pacient.rodne_cislo)
            db.session.add(objednavka)
            db.session.flush()
            ukon = Vykon(nazev=request.form.get("nazov_ukonu"), id_terminu=objednavka.id_terminu)
            db.session.add(ukon)
            db.session.commit()
            session["message"] = "Objednávka bola úspešne pridaná do databázy..."
            return redirect(url_for("objednavky"))
        except Exception as e:
            if session["message"]:
                return redirect(url_for("objednavky"))
            return abort(404)
    else:
        return abort(404)


@app.route("/api/pacient", methods=["POST"])
def pacient_api():
    if current_user.is_authenticated and (current_user.user_type == "S" or current_user.user_type == "D"):
        if request.form.get("rodne_cislo") and request.form.get("kod_pojistovny") and request.form.get("email") \
            and request.form.get("meno") and request.form.get("priezvisko") and request.form.get("adresa") \
                and request.form.get("telefon") and request.form.get("pohlavie") and request.form.get("datum_narodenia"):
            pacient = db.session.query(Pacient).filter(Pacient.rodne_cislo == int(request.form.get("rodne_cislo"))).first()
            if pacient:
                pacient.kod_pojistovny = int(request.form.get("kod_pojistovny"))
                pacient.email = request.form.get("email")
                pacient.jmeno = request.form.get("meno")
                pacient.prijmeni = request.form.get("priezvisko")
                pacient.adresa = request.form.get("adresa")
                pacient.telefon = request.form.get("telefon")
                pacient.pohlavi = request.form.get("pohlavie")
                pacient.datum_narozeni = datetime.datetime.strptime(request.form.get("datum_narodenia"), '%Y-%m-%d')
                db.session.add(pacient)
                db.session.commit()
                session["message"] = "Pacient bol úspešne upravený"
                return redirect("/pacient/" + request.form.get("rodne_cislo")), 302
            else:
                novy_pacient = Pacient(rodne_cislo=int(request.form.get("rodne_cislo")), kod_pojistovny=int(request.form.get("kod_pojistovny")), \
                    email=request.form.get("email"), jmeno=request.form.get("meno"), prijmeni=request.form.get("priezvisko"), \
                    pohlavi=request.form.get("pohlavie"), adresa=request.form.get("adresa"), telefon=request.form.get("telefon"), \
                    datum_narozeni=datetime.datetime.strptime(request.form.get("datum_narodenia"), '%Y-%m-%d'))

                if request.form.get("prakticky_lekar"):
                    cudzi_pacient = CudziPacient(rodne_cislo=int(request.form.get("rodne_cislo")), meno_praktickeho_lekara=request.form.get("prakticky_lekar"))
                    db.session.add(novy_pacient)
                    db.session.add(cudzi_pacient)
                    db.session.commit()
                else:
                    db.session.add(novy_pacient)
                    db.session.add(RegistrovanyPacient(rodne_cislo=int(request.form.get("rodne_cislo")), datum_registracie=datetime.datetime.now()))
                    db.session.commit()
                session["message"] = "Pacient bol úspešne vytvorený."
                return redirect("/pacient/" + request.form.get("rodne_cislo")), 302

    return abort(404)


@app.route("/api/pacienti", methods=["GET"])
def pacienti_api():
    if current_user.is_authenticated and (current_user.user_type == "S" or current_user.user_type == "D"):
        if "registrovani" in request.args:
            pacienti = [{"name": i.jmeno + " " + i.prijmeni + " (" + str(i.rodne_cislo) + ")", "id": i.rodne_cislo}
                for i in db.session.query(Pacient.jmeno, Pacient.prijmeni, Pacient.rodne_cislo).select_from(Pacient).join(RegistrovanyPacient).all()]
            return jsonify(pacienti), 200
        else:
            pacienti = [{"name": i.jmeno + " " + i.prijmeni + " (" + str(i.rodne_cislo) + ")", "id": i.rodne_cislo} for i in db.session.query(Pacient).all()]
            return jsonify(pacienti), 200
    else:
        return abort(404)


@app.route("/api/user", methods=["GET", "POST"])
def add_user():
    if current_user.is_authenticated and current_user.user_type == "A" and request.method == "POST":
        user = User.query.filter(User.username == request.form.get("username")).first()
        if user:
            heslo = request.form.get("password") if request.form.get("password") else None
            user.meno = request.form.get("meno")
            user.priezvisko = request.form.get("priezvisko")
            user.user_type = request.form.get("type")

            if heslo:
                user.password = hashlib.md5(heslo.encode('utf-8')).hexdigest()
            db.session.add(user)
            db.session.commit()
            session["message"] = "Užívateľ bol úspešne upravený."
            return redirect(url_for("index"))
        else:
            heslo = request.form.get("password")
            db.session.add(User(username=request.form.get("username"), meno=request.form.get("meno"),
                                priezvisko=request.form.get("priezvisko"), password=hashlib.md5(heslo.encode('utf-8')).hexdigest(), user_type=request.form.get("type")))
            db.session.commit()
            session["message"] = "Nový doktor bol úspešne pridaný do databázy." if request.form.get("type") == "D" \
                else "Nová sestrička bola úspešne pridaná do databázy."
            return redirect(url_for("index"))
    elif current_user.is_authenticated and current_user.user_type == "A" and request.method == "GET":
        if "password" in request.args:
            user = User.query.filter(User.id == current_user.id).first()
            heslo = request.args["password"]
            user.password = hashlib.md5(heslo.encode('utf-8')).hexdigest()
            db.session.add(user)
            db.session.commit()
            logout_user()
            return redirect(url_for("index"))
        else:
            abort(404)

    else:
        return abort(404)


@app.route("/api/user/<id>", methods=["GET"])
def user(id):
    if current_user.is_authenticated and current_user.user_type == "A":
        user = User.query.filter(User.id == id).first()
        if "remove" in request.args:
            if user:
                db.session.delete(user)
                db.session.commit()
                session["message"] = "Užívateĺ bol úspešne odstránený."
            return redirect("/")
        else:
            if user:
                return jsonify({
                    "meno": user.meno,
                    "priezvisko": user.priezvisko,
                    "username": user.username
                }), 200
            else:
                return abort(404)
    else:
        return abort(404)


@app.route("/pacienti", methods=["GET"])
def pacienti():
    """
    Endpoint pre pacientov, zobrazi tabulku a umozni filtraciu
    :return:
    """

    if current_user.is_authenticated:
        user_type = current_user.user_type
        if "cudzi" in request.args:
            return render_template("pacienti.html", context=db.session.query(Pacient).join(CudziPacient).all(), heading="Pacienti",
                                   pacienti={"registrovani": "", "cudzi": "active", "vsetci": ""}, user_type=user_type)
        elif "registrovani" in request.args:
            return render_template("pacienti.html", context=db.session.query(Pacient).join(RegistrovanyPacient).all(), heading="Pacienti",
                                   pacienti={"registrovani": "active", "cudzi": "", "vsetci": ""}, user_type=user_type)
        else:
            return render_template("pacienti.html", context=db.session.query(Pacient).all(), heading="Pacienti",
                                   pacienti={"registrovani": "", "cudzi": "", "vsetci": "active"}, user_type=user_type)

    else:
        return redirect(url_for("index"))


@app.route("/pacient/<cislo_pacienta>")
def pacient(cislo_pacienta):
    """
    Zobrazi profil pacienta
    :return:
    """
    if current_user.is_authenticated:
        user_type = current_user.user_type
        dktr = False
        if user_type == "D":
            dktr = True

        if "remove" in request.args:
            cudzi_pacient = CudziPacient.query.filter(CudziPacient.rodne_cislo == cislo_pacienta).first()
            if cudzi_pacient:
                Objednavka.query.filter(Objednavka.rodne_cislo == cudzi_pacient.rodne_cislo).delete()
                Navsteva.query.filter(Navsteva.rodne_cislo == cudzi_pacient.rodne_cislo).delete()
                Faktura.query.filter(Faktura.rodne_cislo == cudzi_pacient.rodne_cislo).delete()
                db.session.delete(cudzi_pacient)
                db.session.commit()
            else:
                registrovany_pacient = RegistrovanyPacient.query.filter(RegistrovanyPacient.rodne_cislo == cislo_pacienta).first()
                Objednavka.query.filter(Objednavka.rodne_cislo == registrovany_pacient.rodne_cislo).delete()
                Navsteva.query.filter(Navsteva.rodne_cislo == registrovany_pacient.rodne_cislo).delete()
                Faktura.query.filter(Faktura.rodne_cislo == registrovany_pacient.rodne_cislo).delete()
                db.session.delete(registrovany_pacient)
                db.session.commit()
            if "sillently" in request.args:
                return jsonify({"response": "True"}), 200
            else:
                session["message"] = "Pacient s rodným číslo {} bol úspešne odstránený.".format(cislo_pacienta)
                return redirect(url_for("index"))

        else:
            tabulka = []

            for i in db.session.query(Objednavka.id_terminu, Objednavka.datum, Pacient.jmeno, Pacient.prijmeni, RegistrovanyPacient.rodne_cislo).join(
                    RegistrovanyPacient).join(Pacient).filter(Pacient.rodne_cislo == cislo_pacienta).all():

                ukon = db.session.query(Vykon).filter(Vykon.id_terminu == int(i[0])).first()

                if not ukon or ukon.vysledek:
                    continue

                current = {
                    "id_terminu": i[0],
                    "datum": i[1].strftime("%Y-%m-%dT%H:%M:%S")[:-3].replace("T", " "),
                    "jmeno": i[2] + " " + i[3],
                    "rodne_cislo": i[4],
                    "title": i[2] + " " + i[3],
                    "start": i[1].strftime("%Y-%m-%dT%H:%M:%S")[:-3],
                    "ukon": ukon.nazev,
                    "id_ukonu": ukon.id_ukonu
                }
                tabulka.append(current)

            navstevy = db.session.query(Navsteva).filter(Navsteva.rodne_cislo == cislo_pacienta).all()

            message = None
            try:
                message = session["message"]
                session.pop("message", None)
            except KeyError:
                pass
            if not Pacient.query.filter(Pacient.rodne_cislo == cislo_pacienta).first():
                return abort(404)
            if navstevy:
                for i in navstevy:
                    i.lieky = db.session.query(Predepsal, Liek).join(Liek).filter(Predepsal.id_navstevy == i.id_navstevy).all()
                    i.ukony = Vykon.query.filter(Vykon.id_navstevy == i.id_navstevy).all()

            registrovany_pacient = db.session.query(RegistrovanyPacient).filter(RegistrovanyPacient.rodne_cislo == cislo_pacienta).first()
            registrovany = True if registrovany_pacient else False
            cudzi_pacient = None
            if not registrovany:
                cudzi_pacient = db.session.query(CudziPacient).filter(CudziPacient.rodne_cislo == cislo_pacienta).first()
            return render_template("pacient.html", context=Pacient.query.filter(Pacient.rodne_cislo == cislo_pacienta).first(), heading="Pacient",
                                   navstevy=navstevy, doktor=dktr, message=message, user_type=user_type, tabulka=tabulka, objednavky=objednavky, registrovany=registrovany,
                                    cudzi_pacient=cudzi_pacient, odborne_vysetrenie=OdborneVysetrenie.query.filter(OdborneVysetrenie.rodne_cislo == cislo_pacienta),
                                    faktury=Faktura.query.filter(Faktura.rodne_cislo == cislo_pacienta).all())
    else:
        return redirect(url_for("index"))


@app.route("/lieky")
def lieky():
    """
    Zobrazi stranku s liekmi
    :return:
    """
    if current_user.is_authenticated and (current_user.user_type == "D" or current_user.user_type == "S"):
        message = None
        try:
            message = session["message"]
            session.pop("message", None)
        except KeyError:
            pass

        user_type = current_user.user_type
        return render_template("lieky.html", message=message, context=Liek.query.all(), heading="Lieky",user_type=user_type)
    else:
        return redirect(url_for("index"))


@app.route("/api/faktura", methods=["POST"])
def api_faktura():
    if current_user.is_authenticated and (current_user.user_type == "D" or current_user.user_type == "S"):
        try:
            try:
                datum_vystaveni = datetime.datetime.strptime(request.form.get("datum_vystavenia"), '%m/%d/%Y')
            except:
                datum_vystaveni = datetime.datetime.strptime(request.form.get("datum_vystavenia"), '%Y-%m-%d')

            try:
                datum_splatnosti = datetime.datetime.strptime(request.form.get("datum_splatnosti"), '%m/%d/%Y')
            except:
                datum_splatnosti = datetime.datetime.strptime(request.form.get("datum_splatnosti"), '%Y-%m-%d')

            if request.form.get("cislo_faktury"):
                print("12")
                faktura = db.session.query(Faktura).filter(Faktura.cislo_faktury == int(request.form.get("cislo_faktury"))).first()
                faktura.castka = int(request.form.get("ciastka"))
                faktura.datum_splatnosti = datum_splatnosti
                faktura.datum_vystaveni = datum_vystaveni
                faktura.konstatni_symbol = int(request.form.get("konstantni_symbol"))
                faktura.variabilny_symbol = int(request.form.get("variabilny_symbol"))
                session["message"] = "Faktúra bola úspešne upravená."
                db.session.add(faktura)
                db.session.commit()
                if request.form.get("pacient-faktura"):
                    return redirect("/faktury")

                return redirect("/pacient/" + str(faktura.rodne_cislo))
            else:
                print("14")
                faktura = Faktura(
                    castka=int(request.form.get("ciastka")),
                    datum_splatnosti=datum_splatnosti,
                    datum_vystaveni=datum_vystaveni,
                    konstatni_symbol=int(request.form.get("konstantni_symbol")),
                    variabilny_symbol=int(request.form.get("variabilny_symbol")),
                    rodne_cislo=int(request.form.get("rodne_cislo"))

                )
                session["message"] = "Faktúra bola úspešne pridaná."

            db.session.add(faktura)
            db.session.commit()
            if request.form.get("pacient-faktura"):
                return redirect("/faktury")
            return redirect("/pacient/" + str(faktura.rodne_cislo))
        except Exception as e:
            print(e)
            session["message"] = "Chyba pri spracovani formulára. Prosím zadajte platné hodnoty"
            return redirect("/pacient/" + request.form.get("rodne_cislo"))

    return abort(404)


@app.route("/api/faktura/<id>", methods=["GET"])
def api_faktury(id):
    if current_user.is_authenticated and (current_user.user_type == "D" or current_user.user_type == "S"):
        if request.method == "GET":
            if "remove" in request.args:
                faktura = Faktura.query.filter(Faktura.cislo_faktury == id).first()
                if faktura:
                    db.session.delete(faktura)
                    db.session.commit()
                    session["message"] = "Faktúra bola úspešne odstránená..."
                    if "faktury" in request.args:
                        return redirect("/faktury")

                    return redirect("/pacient/" + str(faktura.rodne_cislo))
            elif "print" in request.args:
                faktura = Faktura.query.filter(Faktura.cislo_faktury == id).first()
                pacient = Pacient.query.filter(Pacient.rodne_cislo == faktura.rodne_cislo).first()
                return render_template("faktura-tisk.html", pacient=pacient, faktura=faktura)

            else:
                faktura = Faktura.query.filter(Faktura.cislo_faktury == id).first()
                pacient = Pacient.query.filter(Pacient.rodne_cislo == faktura.rodne_cislo).first()
                if faktura:
                    return jsonify({
                        "cislo_faktury": faktura.cislo_faktury,
                        "variabilny_symbol": faktura.variabilny_symbol,
                        "konstantni_symbol": faktura.konstatni_symbol,
                        "ciastka": faktura.castka,
                        "datum_vystavenia": faktura.datum_vystaveni.strftime('%m/%d/%Y'),
                        "datum_splatnosti": faktura.datum_splatnosti.strftime('%m/%d/%Y'),
                        "rodne_cislo": faktura.rodne_cislo,
                        "meno": pacient.jmeno + " " + pacient.prijmeni
                    }), 200
                else:
                    return jsonify({"request": "Bad request. Try again..."}), 404
    return abort(404)


@app.route("/faktury")
def faktury():
    """
    Zobrazi stranku s objednavkami
    :return:
    """
    message = None
    try:
        message = session["message"]
        session.pop("message", None)
    except KeyError:
        pass

    if current_user.is_authenticated and (current_user.user_type == "S" or current_user.user_type == "D"):
        faktury = db.session.query(Faktura, Pacient).join(Pacient).filter(Pacient.rodne_cislo == Faktura.rodne_cislo).all()
        user_type = current_user.user_type
        return render_template("faktury.html", heading="Faktúry", user_type=user_type, message=message, faktury=faktury)
    else:
        return redirect(url_for("index"))


@app.route("/objednavky")
def objednavky():
    """
    Zobrazi stranku s objednavkami`
    :return:
    """
    message = None
    try:
        message = session["message"]
        session.pop("message", None)
    except KeyError:
        pass

    context = []

    if "zaciatok" in request.args:
        zaciatok = datetime.datetime.strptime(request.args["zaciatok"], '%m/%d/%Y')
    else:
        zaciatok = datetime.datetime.strptime("1990-01-01 00:00:00", '%Y-%m-%d %H:%M:%S')

    if "koniec" in request.args:
        koniec = datetime.datetime.strptime(request.args["koniec"], '%m/%d/%Y')
    else:
        koniec = datetime.datetime.strptime("2050-01-01 00:00:00", '%Y-%m-%d %H:%M:%S')
    koniec = koniec.replace(hour=23, minute=59, second=59)
    for i in db.session.query(Objednavka.id_terminu, Objednavka.datum, Pacient.jmeno, Pacient.prijmeni, RegistrovanyPacient.rodne_cislo).join(RegistrovanyPacient)\
            .join(Pacient).filter(Objednavka.datum >= zaciatok).filter(Objednavka.datum <= koniec).all():
        current = {
            "id_terminu": i[0],
            "datum": str(i[1])[:-3],
            "jmeno": i[2] + " " + i[3],
            "rodne_cislo": i[4],
            "title": i[2] + " " + i[3],
            "start": i[1].strftime("%Y-%m-%dT%H:%M:%S"),
        }
        context.append(current)
    if current_user.is_authenticated and (current_user.user_type == "S" or current_user.user_type == "D"):
        tabulka = False
        if "tabulka" in request.args:
            tabulka = True

        user_type = current_user.user_type
        return render_template("objednavky.html", context=context, heading="Objednávky", user_type=user_type, message=message, tabulka=tabulka)
    else:
        return redirect(url_for("index"))


@app.route("/api/ukony", methods=["POST"])
def pridat_ukon():
    if current_user.is_authenticated and (current_user.user_type == "S" or current_user.user_type == "D"):
        if request.form.get("nazev_ukonu") and request.form.get("popis_ukonu") and request.form.get("popis_ukonu") and request.form.get("vysledok_ukonu"):
            ukon = Vykon(nazev=request.form.get("nazev_ukonu"), popis=request.form.get("popis_ukonu"), vysledek=request.form.get("vysledok_ukonu"), id_navstevy=request.form.get("id_navstevy"))
            navsteva = Navsteva.query.filter(Navsteva.id_navstevy == request.form.get("id_navstevy")).first()
            db.session.add(ukon)
            db.session.commit()
            session["message"] = "Úkon bol úspešne pridaný do databázy."
            return redirect("/pacient/{}".format(navsteva.rodne_cislo), 302)
        else:
            return abort(404)
    else:
        return abort(404)


@app.route("/api/navsteva", methods=["POST", "GET"])
def navsteva():
    if request.method == "POST" and current_user.is_authenticated and (current_user.user_type == "S" or current_user.user_type == "D"):
        datum = None
        try:
            datum = datetime.datetime.strptime(request.form.get("datum") + " " + request.form.get("cas"), '%m/%d/%Y %H:%M:%S')
        except:
            datum = datetime.datetime.strptime(request.form.get("datum") + " " + request.form.get("cas"), '%Y-%m-%d %H:%M:%S')

        if datum:
            db.session.add(Navsteva(rodne_cislo=int(request.form.get("pacient_id").strip()), datum=datum))
            db.session.commit()
            session["message"] = "Návšteva bola úspešne pridaná do databázy."
            return redirect("/pacient/{}".format(request.form.get("pacient_id")), 302)
        else:
            return abort(404)

    elif request.method == "GET" and current_user.is_authenticated and (current_user.user_type == "S" or current_user.user_type == "D"):
        if "id" in request.args and "delete" in request.args:
            navsteva = db.session.query(Navsteva).filter(Navsteva.id_navstevy == int(request.args["id"])).first()
            rc = navsteva.rodne_cislo
            db.session.delete(navsteva)
            db.session.commit()
            session["message"] = "Návšteva bola úspešne odstránená."
            return redirect("/pacient/{}".format(rc), 302)

    else:
        return abort(404)


@app.route("/api/predepsal/<id>", methods=["GET"])
def api_predepsal(id):
    if current_user.is_authenticated and (current_user.user_type == "S" or current_user.user_type == "D"):
        try:
            id_lieku = int(id.split("-")[0])
            id_navstevy = int(id.split("-")[1])
            predepsal = db.session.query(Predepsal).filter(Predepsal.id_lieku == id_lieku).filter(Predepsal.id_navstevy == id_navstevy).first()
            liek = db.session.query(Liek).filter(Liek.id_lieku == id_lieku).first()
            navsteva = db.session.query(Navsteva).filter(Navsteva.id_navstevy == id_navstevy).first()
            if not predepsal:
                return abort(404)
            if "remove" in request.args:
                db.session.delete(predepsal)
                db.session.commit()
                session["message"] = "Predpísaný liek bol úspeśne vymazaný."
                return redirect("/pacient/" + str(navsteva.rodne_cislo)), 302

            response = {
                "id_navstevy": id_navstevy,
                "liek": liek.nazov,
                "id_lieku": liek.id_lieku,
                "mnozstvo": predepsal.mnozstvi
            }

            return jsonify(response), 200

        except:
            session["message"] = "Nepodarilo sa spracovať formulár."

    return abort(404)


@app.route("/api/lieky", methods=["GET", "POST"])
def api_lieky():
    if current_user.is_authenticated:
        if request.method == "GET":
            lieky = [{"nazov": i.nazov, "id": i.id_lieku} for i in Liek.query.all()]
            return jsonify(lieky), 200
        else:
            if not request.form.get("id_lieku"):
                session["message"] = "Zadaný liek neexistuje."
                return redirect("/pacient/" + request.form.get("rodne_cislo"))

            predepsal = db.session.query(Predepsal).filter(Predepsal.id_navstevy == int(request.form.get("id_navstevy"))).filter(Predepsal.id_lieku == int(request.form.get("id_lieku"))).first()
            if predepsal:
                db.session.add(predepsal)
                db.session.commit()
                session["message"] = "Predepasaný liek bol úspešne upravený"
                return redirect("/pacient/" + request.form.get("rodne_cislo"))
            else:
                predepsal = Predepsal(id_navstevy=int(request.form.get("id_navstevy")), id_lieku=int(request.form.get("id_lieku")), mnozstvi=int(request.form.get("mnozstvo")))
                db.session.add(predepsal)
                db.session.commit()
                session["message"] = "Predepasaný liek bol úspešne pridaný do databázy."
                return redirect("/pacient/" + request.form.get("rodne_cislo"))

    return abort(404)


@app.route("/api/ockovanie", methods=["POST"])
def ockovanie():
    if current_user.is_authenticated:
        if request.method == "GET":
            pass
        else:
            try:
                datum = datetime.datetime.strptime(request.form.get("datum_platnosti"), '%m/%d/%Y')
            except:
                datum = datetime.datetime.strptime(request.form.get("datum_platnosti"), '%Y-%m-%d')
            if not request.form.get("id_ockovania"):
                ukon = Vykon(
                    nazev=request.form.get("nazev_ukonu"),
                    popis=request.form.get("popis_ukonu"),
                    vysledek=request.form.get("vysledok_ukonu"),
                    id_navstevy=int(request.form.get("id_navstevy_ockovanie"))
                )
                db.session.add(ukon)
                db.session.flush()
                ockovanie = Ockovani(
                    id_ukonu=ukon.id_ukonu,
                    doba_ucinnosti=datum,
                    davka=int(request.form.get("davka"))
                )
                db.session.add(ockovanie)
                db.session.commit()
                session["message"] = "Očkovanie bolo úspešne pridané."
                return redirect("/pacient/" + request.form.get("rodne_cislo"))

            else:
                ukon = db.session.query(Vykon).filter(Vykon.id_ukonu == int(request.form.get("id_ockovania"))).first()
                ukon.nazev = request.form.get("nazev_ukonu")
                ukon.popis = request.form.get("popis_ukonu")
                ukon.vysledek = request.form.get("vysledok_ukonu")
                db.session.add(ukon)
                db.session.flush()
                ockovanie = db.session.query(Ockovani).filter(Ockovani.id_ukonu == ukon.id_ukonu).first()
                ockovanie.doba_ucinnosti = datum
                ockovanie.davka=int(request.form.get("davka"))
                db.session.add(ockovanie)
                db.session.commit()
                session["message"] = "Očkovanie bolo úspešne aktualizované."
                return redirect("/pacient/" + request.form.get("rodne_cislo"))

    return abort(404)


@app.route("/api/prohlidka", methods=["POST"])
def prohldika():
    if current_user.is_authenticated:
        if request.method == "GET":
            pass
        else:
            try:
                datum = datetime.datetime.strptime(request.form.get("datum_platnosti"), '%m/%d/%Y')
            except:
                datum = datetime.datetime.strptime(request.form.get("datum_platnosti"), '%Y-%m-%d')
            if not request.form.get("id_prohlidky"):
                ukon = Vykon(
                    nazev=request.form.get("nazev_ukonu"),
                    popis=request.form.get("popis_ukonu"),
                    vysledek=request.form.get("vysledok_ukonu"),
                    id_navstevy=int(request.form.get("id_navstevy_prohlidka"))
                )

                db.session.add(ukon)
                db.session.flush()
                prohlidka = PravidelnaProhlidka(
                    id_ukonu=ukon.id_ukonu,
                    doba_ucinnosti=datum,
                    vyska=int(request.form.get("vyska")),
                    vaha=int(request.form.get("vaha"))
                )
                db.session.add(prohlidka)
                db.session.commit()
                session["message"] = "Pravidelná prohlídka bola úspešne pridané."
                return redirect("/pacient/" + request.form.get("rodne_cislo"))

            else:
                ukon = db.session.query(Vykon).filter(Vykon.id_ukonu == int(request.form.get("id_ockovania"))).first()
                ukon.nazev = request.form.get("nazev_ukonu")
                ukon.popis = request.form.get("popis_ukonu")
                ukon.vysledek = request.form.get("vysledok_ukonu")
                db.session.add(ukon)
                db.session.flush()
                prohlidka = db.session.query(PravidelnaProhlidka).filter(PravidelnaProhlidka.id_ukonu == ukon.id_ukonu).first()
                prohlidka.doba_ucinnosti = datum
                prohlidka.vyska = int(request.form.get("vyska"))
                prohlidka.vyska = int(request.form.get("vaha"))
                db.session.add(prohlidka)
                db.session.commit()
                session["message"] = "Pravidelná prohlídka bola úspešne aktualizované."
                return redirect("/pacient/" + request.form.get("rodne_cislo"))

    return abort(404)


@app.route("/api/ukony/<id_ukonu>", methods=["POST", "GET"])
def ukony(id_ukonu):
    """
    Zobrazi stranku s objednavkami
    :return:
    """
    if current_user.is_authenticated:
        if request.method == "POST":
            ukon = Vykon.query.filter(Vykon.id_ukonu == id_ukonu).first()
            if not ukon:
                abort(404)
            ukon.nazev = request.form.get("nazev_ukonu") if request.form.get("nazev_ukonu") else ukon.nazev
            ukon.popis = request.form.get("popis_ukonu") if request.form.get("popis_ukonu") else ukon.popis
            ukon.vysledek = request.form.get("vysledok_ukonu") if request.form.get("vysledok_ukonu") else ukon.vysledek
            navsteva = Navsteva.query.filter(Navsteva.id_navstevy == ukon.id_navstevy).first()

            if not ukon.id_navstevy and ukon.id_terminu:
                objednavka = db.session.query(Objednavka).filter(Objednavka.id_terminu == ukon.id_terminu).first()
                navsteva = Navsteva(datum=objednavka.datum, rodne_cislo=objednavka.rodne_cislo)
                db.session.add(navsteva)
                db.session.flush()
                ukon.id_navstevy = navsteva.id_navstevy
                db.session.add(ukon)
                db.session.commit()
                return redirect("/pacient/{}".format(objednavka.rodne_cislo), 302)

            db.session.add(ukon)
            db.session.commit()
            return redirect("/pacient/{}".format(navsteva.rodne_cislo), 302)

        elif "delete" in request.args:
            ukon = Vykon.query.filter(Vykon.id_ukonu == id_ukonu).first()
            navsteva = Navsteva.query.filter(Navsteva.id_navstevy == ukon.id_navstevy).first()

            ockovanie = Ockovani.query.filter(Ockovani.id_ukonu == id_ukonu).first()
            if ockovanie:
                db.session.delete(ockovanie)
                db.session.commit()

            prohlidka = PravidelnaProhlidka.query.filter(PravidelnaProhlidka.id_ukonu == id_ukonu).first()
            if prohlidka:
                db.session.delete(prohlidka)
                db.session.commit()

            db.session.delete(ukon)
            db.session.commit()
            session["message"] = "Úkon s poradovým číslom {} bol úspešne odstránený.".format(id_ukonu)
            return redirect("/pacient/{}".format(navsteva.rodne_cislo), 302)

        else:
            ukon = Vykon.query.filter(Vykon.id_ukonu == id_ukonu).first()
            if ukon:
                response = {
                    "nazev": ukon.nazev,
                    "popis": ukon.popis,
                    "vysledek": ukon.vysledek,
                    "vaha": "",
                    "vyska": "",
                    "doba_ucinnosti_prohlidka": "",
                    "doba_ucinnosti_ockovanie": "",
                    "davka": ""

                }

                prohlidka = PravidelnaProhlidka.query.filter(PravidelnaProhlidka.id_ukonu == id_ukonu).first()
                if prohlidka:
                    response["doba_ucinnosti_prohlidka"] = prohlidka.doba_ucinnosti.strftime('%m/%d/%Y')
                    response["vyska"] = prohlidka.vyska
                    response["vaha"] = prohlidka.vaha

                ockovanie = Ockovani.query.filter(Ockovani.id_ukonu == id_ukonu).first()
                if ockovanie:
                    response["doba_ucinnosti_ockovanie"] = ockovanie.doba_ucinnosti.strftime('%m/%d/%Y')
                    response["davka"] = ockovanie.davka

                return jsonify(response), 200
            else:
                return jsonify({
                    "request": "Bad request. Try again..."
                }), 404
    else:
        return redirect(url_for("index"))


@app.route("/api/odborne_vysetrenie", methods=["POST"])
def odborne_vysetrenie():
    try:
        if current_user.is_authenticated and (current_user.user_type == "S" or current_user.user_type == "D"):
            try:
                try:
                    datum = datetime.datetime.strptime(request.form.get("datum"), '%m/%d/%Y')
                except:
                    datum = datetime.datetime.strptime(request.form.get("datum"), '%Y-%m-%d')
            except:
                session["message"] = "Nesprávny formát dátum alebo času..."
                raise

            if request.form.get("id_odborneho_vysetrenia"):
                odborne_vysetrenie = db.session.query(OdborneVysetrenie).filter(OdborneVysetrenie.id_vysetrenia == int(request.form.get("id_odborneho_vysetrenia"))).first()
                odborne_vysetrenie.nazev = request.form.get("nazev_odborneho_vysetrenia")
                odborne_vysetrenie.popis = request.form.get("popis_odborneho_vysetrenia")
                odborne_vysetrenie.vysledek = request.form.get("vysledok_odborneho_vysetrenia")
                odborne_vysetrenie.pracoviste = request.form.get("pracoviste")
                odborne_vysetrenie.datum = datum
                db.session.add(odborne_vysetrenie)
                db.session.commit()
                session["message"] = "Odborné vyšetrenie bolo úspešne aktualizované."
                return redirect("/pacient/" + request.form.get("rodne_cislo"))

            else:
                odborne_vysetrenie = OdborneVysetrenie(
                    nazev=request.form.get("nazev_odborneho_vysetrenia"),
                    popis=request.form.get("popis_odborneho_vysetrenia"),
                    vysledek=request.form.get("vysledok_odborneho_vysetrenia"),
                    pracoviste=request.form.get("pracoviste"),
                    datum=datum,
                    rodne_cislo=request.form.get("rodne_cislo")
                )

                db.session.add(odborne_vysetrenie)
                db.session.commit()
                session["message"] = "Odborné vyšetrenie bolo úspešne pridané."
                return redirect("/pacient/" + request.form.get("rodne_cislo"))

        else:
            return abort(404)
    except Exception as e:
        print(e)
        return redirect("/pacient/" + request.form.get("rodne_cislo"))


@app.route("/api/odborne_vysetrenie/<id_ukonu>", methods=["GET"])
def odborne_vysetrenia(id_ukonu):
    if current_user.is_authenticated and (current_user.user_type == "S" or current_user.user_type == "D"):
        vysetrenie = OdborneVysetrenie.query.filter(OdborneVysetrenie.id_vysetrenia == id_ukonu).first()
        if "delete" in request.args:
            rc = vysetrenie.rodne_cislo
            db.session.delete(vysetrenie)
            db.session.commit()
            session["message"] = "Odborné vyšetrenie bolo úspešne odstránené."
            return redirect("/pacient/" + str(rc))

        response = {
            "nazov": vysetrenie.nazev,
            "popis": vysetrenie.popis,
            "vysledok": vysetrenie.vysledek,
            "pracoviste": vysetrenie.pracoviste,
            "datum": vysetrenie.datum,
            "rodne_cislo": vysetrenie.rodne_cislo,
        }
        return jsonify(response), 200
    else:
        return redirect(url_for("index"))


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