import sqlite3
from fastapi import FastAPI
from fastapi import Request, Form
from fastapi.responses import HTMLResponse, RedirectResponse

DB_PATH = "./data/database.db"

conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute(
    "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, login TEXT NOT NULL UNIQUE, password TEXT NOT NULL)"
)

app = FastAPI(
    docs_url=None,  # Disable Swagger UI
    redoc_url=None,  # Disable ReDoc
    openapi_url=None,  # Disable OpenAPI JSON schema
)

STYLES = """
<style>
body {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 100vh;
}
</style>
"""


@app.get("/register", response_class=HTMLResponse)
async def register_form():
    return f"""
    <html>
    <head><title>Регистрация</title>{STYLES}</head>
    <body>
    <h2>Регистрация</h2>
    <form action="/register" method="post">
        <input name="login" placeholder="Login" required><br>
        <input name="password" type="password" placeholder="Password" required><br>
        <button type="submit">Register</button>
    </form>
    <p>Уже есть аккаунт? <a href="/login">Войти</a></p>
    </body>
    </html>
    """


@app.post("/register")
async def register(login: str = Form(...), password: str = Form(...)):
    try:
        cursor.execute(
            f"INSERT INTO users (login, password) VALUES ('{login}', '{password}')"
        )
        conn.commit()
        response = RedirectResponse(url="/welcome", status_code=302)
        response.set_cookie("login", login)
        response.set_cookie("password", password)
        return response
    except sqlite3.IntegrityError:
        return HTMLResponse(
            f"""
        <html>
        <head><title>Ошибка регистрации</title>{STYLES}</head>
        <body>
        <h3>Login уже существует</h3>
        <a href='/register'>Попробовать снова</a>
        </body>
        </html>
        """,
            status_code=400,
        )


@app.get("/login", response_class=HTMLResponse)
async def login_form():
    return f"""
    <html>
    <head><title>Вход</title>{STYLES}</head>
    <body>
    <h2>Вход</h2>
    <form action="/login" method="post">
        <input name="login" placeholder="Login" required><br>
        <input name="password" type="password" placeholder="Password" required><br>
        <button type="submit">Login</button>
    </form>
    <p>Нет аккаунта? <a href="/register">Зарегистрироваться</a></p>
    </body>
    </html>
    """


@app.post("/login")
async def login(login: str = Form(...), password: str = Form(...)):
    cursor.execute(
        f"SELECT login FROM users WHERE login='{login}' AND password='{password}'"
    )
    user = cursor.fetchall()
    if user:
        response = RedirectResponse(url="/welcome", status_code=302)
        response.set_cookie("login", login)
        response.set_cookie("password", password)
        return response
    else:
        return HTMLResponse(
            f"""
        <html>
        <head><title>Ошибка входа</title>{STYLES}</head>
        <body>
        <h3>Неверные учетные данные</h3>
        <a href='/login'>Попробовать снова</a>
        </body>
        </html>
        """,
            status_code=401,
        )


@app.get("/welcome", response_class=HTMLResponse)
async def welcome(request: Request):
    login = request.cookies.get("login")
    password = request.cookies.get("password")
    if not login or not password:
        return RedirectResponse(url="/login")
    query=f"SELECT login FROM users WHERE login='{login}' AND password='{password}'"
    print(f"executing: {query}")
    cursor.execute(
        query
    )
    user = cursor.fetchall()
    if user:
        return f"""
        <html>
        <head><title>Добро пожаловать</title>{STYLES}</head>
        <body>
        <h1>Привет, {str(user)[3:-4]}</h1>
      <button onclick="
        document.cookie = 'login=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
        document.cookie = 'password=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
        window.location.href = '/login';
    ">Выйти</button>

        </body>
        </html>
        """

    else:
        return RedirectResponse(url="/login")



@app.get("/", include_in_schema=False)
async def root():
    return RedirectResponse(url="/login")
