from flask import Flask,render_template, url_for,request,redirect
import flask as f
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')
#db0=DataBase("search_data.db")
#table=db0.select_all_data()
#db0.reset()
def is_url(url):
    is_url=True
    if  " " in url:
        is_url=False
    return is_url
@app.route("/",methods=["GET","POST"])
def search():
    try:
        db0=DataBase("search_data.db")
        table= db0.select_all_data()
        url_body="" 
        if request.method=="GET":
            # return f"The submit condition is :== {request.args.get('submit','submit')}"
            if request.args.get("is-submitted","")=="Submit":
                #body=str(bot.get_content_from_urls([request.args.get("search-query","")])[0])
                url_body=request.args.get("search-query","")
                if is_url(url_body):
                    print(db0.insert_data(url_body))
                    return redirect(url_body)
            else:
                body=["abcdefghijklmnopqrstuvwxyz"][0]

        return render_template("index.html",url_body=url_body,table=table)
    except BaseException as e:
        # assert e
        return  f"<h1> The error is {e}"
@app.route("/admin",methods=["GET","POST"])
def admin_panel():
    operation=None
    company_name=None
    url=None
    submit=None
    db=DataBase("search_data.db")
    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"]
        if not operation==None:
            match operation:
                case "insert":
                    company_name=db.insert_data(url)
                case "update":
                    company_name=db.update_data(url)
                case _:
                    company_name=db.delete_data(url)
        return render_template("admin-panel.html",table=table,operation=operation,company_name=company_name,url=url)
    except BaseException as e:
        return str(e)
def main():
    #print(f"{'\033[91m'}|---\\##|--|                  |-->
    #print(f"{'\033[92m'}|####\\#|##|                  |__>
    #print(f"{'\033[93m'}|##|\\#\\|##|------  \\ ---- /   >
    #print(f"{'\033[94m'}|##| \\####| |--| |  \\ \\/ /   |>
    #print(f"{'\033[95m'}|##|  \\###| |__| |-- \\  /    | >
    #print(f"{'\033[96m'}|__|   \\__|______|__  \\/     |_>
    app.run(debug=True,host='0.0.0.0', port=5001)	
if __name__ == '__main__':
    pass
    #app.run(host="0.0.0.0",port=5000,debug=True)
    
