"""Settings loader/writer for settings.ini.

settings.ini is the master configuration file (port, secret key, SMTP, paths).
The admin SMTP page reads and writes the [smtp] section of this same file.
"""
import configparser
import os
import secrets
import threading

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
SETTINGS_PATH = os.environ.get("BCT_SETTINGS", os.path.join(BASE_DIR, "settings.ini"))
_lock = threading.Lock()

DEFAULTS = {
    "server": {
        "host": "127.0.0.1",
        "port": "8085",
        "debug": "false",
        "workers": "3",
    },
    "site": {
        "base_url": "https://bandjouncommunitytexas.org",
        "secret_key": "",
        "secure_cookies": "true",
        "database": "instance/bct.db",
        "uploads_dir": "uploads",
        "max_upload_mb": "300",
    },
    "smtp": {
        "host": "smtp.gmail.com",
        "port": "587",
        "username": "bandjouncommunitytexas@gmail.com",
        "password": "",
        "security": "starttls",  # starttls | ssl | none
        "from_email": "bandjouncommunitytexas@gmail.com",
        "from_name": "Bandjoun Community of Texas (BCT)",
        "recipient": "bandjouncommunitytexas@gmail.com",
    },
}


def load():
    """Return a ConfigParser with defaults applied. Creates the file (and a
    random secret key) the first time it is missing."""
    cp = configparser.ConfigParser(interpolation=None, inline_comment_prefixes=(";",))
    cp.read_dict(DEFAULTS)
    if os.path.exists(SETTINGS_PATH):
        cp.read(SETTINGS_PATH, encoding="utf-8")
    changed = False
    if not cp.get("site", "secret_key"):
        cp.set("site", "secret_key", secrets.token_hex(32))
        changed = True
    if changed or not os.path.exists(SETTINGS_PATH):
        save(cp)
    return cp


def save(cp):
    with _lock:
        tmp = SETTINGS_PATH + ".tmp"
        with open(tmp, "w", encoding="utf-8") as fh:
            fh.write("# Bandjoun Community of Texas (BCT) website settings\n")
            fh.write("# The [smtp] section can also be edited from Admin > Settings.\n")
            fh.write("# Changing [server] port requires: sudo systemctl restart bct\n\n")
            cp.write(fh)
        os.replace(tmp, SETTINGS_PATH)
        try:
            os.chmod(SETTINGS_PATH, 0o600)
        except OSError:
            pass


def smtp_settings():
    cp = load()
    return dict(cp.items("smtp"))


def update_smtp(values):
    cp = load()
    for k, v in values.items():
        cp.set("smtp", k, str(v))
    save(cp)


def abs_path(p):
    return p if os.path.isabs(p) else os.path.join(BASE_DIR, p)
