# DO NOT COPY OR SHARE - A3Tech / NCTI course material for enrolled students only.
# project_db.py - a simple database helper for your final project (Module 8)
#
# Keep this file in the SAME folder as your app, then:   import project_db
#
#   project_db.add("members", {"name": "Jada", "phone": "555-0101"})    save one record
#   project_db.get_all("members")                                        every record
#   project_db.query("SELECT name FROM members WHERE paid = 'No'")       your own SELECT
#
# You don't create tables yourself: add() makes the table, and any new columns,
# the first time you save a record. (Creating tables by hand is Level 2.)

import re
import sqlite3

DB_FILE = "project.db"     # your project's database file, next to your app


def _check_name(word):
    """Table and column names: letters, numbers and _ only - like Python variable names."""
    if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", word):
        raise ValueError(f"'{word}' can't be a table or column name. "
                         "Use letters, numbers and _ only, for example fees_paid")
    return word


def query(sql, values=()):
    """Run a SELECT. Gives back the rows as a list of dictionaries."""
    db = sqlite3.connect(DB_FILE)
    db.row_factory = sqlite3.Row
    rows = [dict(row) for row in db.execute(sql, values)]
    db.close()
    return rows


def table_exists(table):
    """True if something has been saved in this table already."""
    rows = query("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?", (table,))
    return len(rows) > 0


def add(table, record):
    """Save one record (a dictionary) in a table. Makes the table and columns if needed."""
    _check_name(table)
    for key in record:
        _check_name(key)
    db = sqlite3.connect(DB_FILE)
    db.execute(f"CREATE TABLE IF NOT EXISTS {table} (id INTEGER PRIMARY KEY)")
    columns_now = [row[1] for row in db.execute(f"PRAGMA table_info({table})")]
    for key in record:
        if key not in columns_now:
            db.execute(f"ALTER TABLE {table} ADD COLUMN {key}")
    columns = ", ".join(record)
    blanks = ", ".join("?" for key in record)
    db.execute(f"INSERT INTO {table} ({columns}) VALUES ({blanks})", list(record.values()))
    db.commit()
    db.close()


def get_all(table):
    """Every record in a table, as a list of dictionaries. [] if nothing is saved yet."""
    _check_name(table)
    if not table_exists(table):
        return []
    return query(f"SELECT * FROM {table}")


def delete_all(table):
    """Throw away a whole table and start again. Careful - there's no undo!"""
    _check_name(table)
    db = sqlite3.connect(DB_FILE)
    db.execute(f"DROP TABLE IF EXISTS {table}")
    db.commit()
    db.close()
