import os
from contextlib import contextmanager

try:
    import pymysql
except ImportError:
    pymysql = None


def get_config():
    if pymysql is None:
        raise RuntimeError(
            "PyMySQL is not installed. Install requirements.txt in the Python app virtualenv."
        )

    return {
        "host": os.getenv("MYSQL_HOST", "127.0.0.1").strip(),
        "port": int(os.getenv("MYSQL_PORT", "3306").strip()),
        "user": os.getenv("MYSQL_USER", "root").strip(),
        "password": os.getenv("MYSQL_PASSWORD", "").strip(),
        "database": os.getenv("MYSQL_DATABASE", "charity_compass").strip(),
        "cursorclass": pymysql.cursors.DictCursor,
    }


def get_public_config():
    config = get_config()
    return {
        "host": config["host"],
        "port": config["port"],
        "user": config["user"],
        "database": config["database"],
        "password_set": bool(config["password"]),
    }


@contextmanager
def get_connection():
    connection = pymysql.connect(**get_config())
    try:
        yield connection
    except pymysql.MySQLError:
        connection.rollback()
        raise
    finally:
        connection.close()


def fetch_one(query, params=None):
    with get_connection() as connection:
        with connection.cursor() as cursor:
            cursor.execute(query, params or ())
            return cursor.fetchone()


def fetch_all(query, params=None):
    with get_connection() as connection:
        with connection.cursor() as cursor:
            cursor.execute(query, params or ())
            return cursor.fetchall()


def execute(query, params=None):
    with get_connection() as connection:
        with connection.cursor() as cursor:
            cursor.execute(query, params or ())
            connection.commit()
            return cursor.lastrowid
