from flask import Blueprint, render_template, request, flash, redirect, url_for, abort, current_app
from markupsafe import Markup
from app.models import Message
from app import db
from uuid import uuid4 as uuid
from app.admin  import Admin
import re
import threading


bp = Blueprint("bp", __name__, template_folder="templates")


@bp.route("/")
def index():
    return render_template("home.html")


@bp.route("/contact", methods=["GET", "POST"])
def contact():
    if request.method == "GET":
        return render_template("contact.html")

    email = request.form.get("email")
    text = request.form.get("message")
    if email is not None and text is not None:
        msg = Message(email=email, text=text, uuid=str(uuid()))
        db.session.add(msg)
        db.session.commit()
        url = url_for("bp.message", message_uuid=msg.uuid)
        flash(Markup("Thank you for your message. You can view it "
                    f"<a href='{url}'>here</a>."))
        admin = Admin(current_app.config["ADMIN_TARGET"], current_app.config["FLAG_COOKIE"])
        threading.Thread(target=admin.visit, args=(url, )).start()
    else:
        flash(Markup("Something is wrong with your message."))
    return redirect(url_for("bp.index"))


@bp.route("/messages/<message_uuid>")
def message(message_uuid):
    msg = Message.query.filter(Message.uuid==message_uuid).first()
    if msg is not None:
        for regex in current_app.config["FILTER"]:
            msg.text = re.subn(regex, "", msg.text,
                               flags=re.DOTALL | re.MULTILINE | re.IGNORECASE)[0]
        return render_template("message_unescaped.html", message=msg)
    else:
        abort(404)


@bp.route("/messages")
def all_messages():
    config = current_app.config
    if config["SUPER_SECRET_ADMIN_PANEL"]:
        cookie = request.cookies.get("flag")
        if cookie is not None and cookie == config["FLAG"]:
            return render_template("all_messages.html", messages=reversed(Message.query.all()))
    abort(403)

