import os
from flask import Flask, redirect, url_for, render_template, request, flash
from .src import host_lookup
from dotenv import load_dotenv
from markupsafe import escape

# Instead of turning 'lookup' into a Blueprint, maybe I could make a history of previous lookups a Blueprint?


def create_app(test_config=None):
    app = Flask(__name__)
    app.config.from_pyfile("config.py")
    load_dotenv()
    app.secret_key = os.getenv("SECRET_KEY")

    if test_config is None:
        app.config.from_pyfile("config.py", silent=True)
    else:
        app.config.update(test_config)

    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    @app.route("/")
    def index():
        # return render_template("index.html")
        return redirect(url_for("lookup"))

    @app.route("/lookup", methods=(["GET", "POST"]))
    def lookup():
        hosts = []
        results = []
        if request.method == "GET":
            return render_template("lookup.html")
        elif request.method == "POST" and any(request.form.get("host")):
            print(f'REQUEST.FORM.GET("HOST") IS {request.form.get("host")}')
            user_input = escape(request.form.get("host").strip())
            hosts, errors = host_lookup.process_input(user_input)
            for host in hosts:
                result = host_lookup.Lookedup(host)
                results.append(result)
            return render_template("results.html", hosts=results, errors=errors)
        else:
            flash("Nothing entered! Try again?", "error")
            return render_template("lookup.html")

    def lookup():
        hosts = []

    #    from . import lookup
    #    app.register_blueprint(lookup.bp)

    return app