from flask import Flask,render_template, url_for,request,redirect
from .crawler import CrawlerBot
import os
from .db import DataBase
#print(dir(request),[[i,dir(i)] for i in dir(request)])
app = Flask(__name__, template_folder='templates')
@app.route('/')
def hello():
    return render_template("index.html")
@app.route("/file-manager", methods=["GET","POST"])
def file_manager():
    pathp="aa"
    if request.method=="POST":
        if request.form["load-file"]=="Load":
            pathp= request.form["file-path"] 
    return render_template("file-manager.html",p=pathp)
@app.route("/file-manager-response",methods=["GET","POST"])
def file_manager_response():
    if request.method=="POST":
        pass
@app.route("/search",methods=["GET","POST"])
def search():
    try:
        bot=CrawlerBot("PythonBot")
        url_body="" 
        if request.method=="GET":
            # return f"The submit condition is :== {request.args.get('submit','submit')}"
            if request.args.get("Submit","")=="Submit":
                body=str(bot.get_content_from_urls([request.args.get("search-query","")])[0])
                url_body=request.args.get("search-query","")

                # os.chdir(os.getcwd()+"/templates")
                # with open("body.html","w") as f:
                   # f.write(body)
                # print(request.args.get("search-query",""))
                return redirect(request.args.get("search-query",""))
            else:
                body=["abcdefghijklmnopqrstuvwxyz"][0]

        return render_template("search.html",url_body=url_body)
    except BaseException as e:
        # assert e
        return  f"<h1> The error is {e}"
@app.route("/body")
def crawled_html0():
    try:
        return render_template("body.html")
    except BaseException as e:
        return redirect(url_for("search"))
        return f"<h1>Crawled_html0 error: {e}</h1>"
@app.route("/admin",methods=["GET","POST"])
def admin_panel():
    operation=None
    company_name=None
    url=None
    submit=None
    db=DataBase("search_data.db")
    db.setup()
    table=db.select_all_data()
    try:
        if request.method=="POST":
            if request.form["submit"]=="Submit":
                operation=request.form["operation"]
                company_name=request.form["company-name"]
                url=request.form["url"]
        return render_template("admin-panel.html",table=table,operation=operation,company_name=company_name,url=url)
    except BaseException as e:
        return str(e)
if __name__ == '__main__':
    pass
    #app.run(host="0.0.0.0",port=5000,debug=True)
    
