import sqlite3
from pathlib import Path

DB_PATH = Path(__file__).parent.parent / "database" / "calendar.db"


def get_connection():
    conn = sqlite3.connect(DB_PATH)

    conn.execute("PRAGMA foreign_keys = ON")

    conn.row_factory = sqlite3.Row

    return conn


def execute(query, params=()):
    with get_connection() as conn:
        cursor = conn.cursor()
        cursor.execute(query, params)
        conn.commit()

        return cursor.lastrowid


def fetch_one(query, params=()):
    with get_connection() as conn:
        cursor = conn.cursor()
        cursor.execute(query, params)

        return cursor.fetchone()


def fetch_all(query, params=()):
    """
    Haalt meerdere resultaten op.
    """
    with get_connection() as conn:
        cursor = conn.cursor()
        cursor.execute(query, params)

        return cursor.fetchall()


def test_connection():
    with get_connection() as conn:
        cursor = conn.cursor()
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")

        return cursor.fetchall()


if __name__ == "__main__":
    print("Database:", DB_PATH)

    tables = test_connection()

    if tables:
        print("Gevonden tabellen:")
        for table in tables:
            print("-", table["name"])
    else:
        print("Geen tabellen gevonden.")


def get_table_names():
    return fetch_all(
        """
        SELECT name
        FROM sqlite_master
        WHERE type = 'table'
        """
    )