from flask import Flask, request, render_template
import subprocess
import glob

app = Flask(__name__)


index_html = """
<a href="/ascii">/ascii</a>
<a href="/figlet/xpub">/figlet<word></a>
<a href="/words">/words</a>
<a href="/find/value">/find/(word)</a>
<a href="/transformations">/transformations</a>
"""

@app.route("/")
def index():
    return index_html

html_template = """
<h1>ascii code points</h1>
<form action="/ascii" method="get">
<input type="text" name="search">
<br><br>
<input type="submit" value="code points">
</form>
"""

@app.route("/ascii")
def ascii():
    # print("request.args.get('search'):", request.args.get("search"))
    if request.args.get("search") == None:
        return html_template
    else:
        search = request.args.get("search")
        result_list = []
        for character in search:
            unicode_point = format(ord(character))
            result_list.append(character + " " + unicode_point)

        result_string = "<br>\n".join(result_list)
        return html_template + f"<pre>{ result_string }</pre>"



@app.route("/figlet/<word>")
def figlet(word):
    # os.system()
    msg = subprocess.run(["figlet", word], capture_output=True).stdout.decode()
    # print(msg)
    return f"<pre>{ msg }</pre>"



@app.route("/words/")
def words():
    texts = glob.glob("./texts/*.txt")
    print(texts)
    for document in texts: 
        with open(document, "r") as d:
            text = d.read()
            words = text.split()
    return render_template('words.html', words=words)

@app.route("/find/<word>")
def find(word):
    texts = glob.glob("./texts/*.txt")
    results = []
    for document in texts: 
        with open(document, "r") as d:
            lines = d.readlines()
            for line in lines:
                if word.lower() in line.lower():
                    line = line.replace(word, f"<strong>{word}</strong>")
                    results.append(line)
    return render_template('find.html', results=results)

@app.route("/transformations", methods=["GET", "POST"])
def transformations():
    print(request.method)
    if request.method == "GET":
        return render_template("transformations.html")
    if request.method == "POST":
        text = request.form["text"]
        transformed_text = text.replace("value", "<strong style='font-size: 64px;'>value</strong>")
        return render_template("transformations.html", transformed_text=transformed_text)
    