# SPDX-FileCopyrightText: 2022 Georg-August-Universität Göttingen
#
# SPDX-License-Identifier: CC0-1.0

"""Configure and start the WSGI DAV Server."""
import logging
import os

import sentry_sdk
from cheroot import wsgi
from wsgidav.wsgidav_app import WsgiDAVApp
from repdav.config import AppConfig

app_config = AppConfig()

if app_config.dsn:
    sentry_sdk.init(
        app_config.dsn,
        traces_sample_rate=1.0
    )

logging.basicConfig(level=logging.DEBUG,
                    format='%(name)s %(levelname)s %(asctime)s %(message)s')
_logger = logging.getLogger(__name__)
_logger.propagate = True

# configure the "wsgidav" named logger
tmp_logger = logging.getLogger("wsgidav")
tmp_logger.propagate = True
tmp_logger.setLevel(logging.DEBUG)

# Configuration of the WsgiDAVApp.
# https://wsgidav.readthedocs.io/en/latest/user_guide_configure.html
# TODO: move to config.py
config = {
    "host": os.getenv("host") or "localhost",
    "port": int(os.getenv("port") or "8080"),
    "provider_mapping": {
        "/": {"class": "repdav.textgrid_named_dav_provider.TextgridNamedResourceProvider"},
    },
    "verbose": 4,
    "http_authenticator": {
        "domain_controller": "repdav.textgrid_domain_controller.TextgridDC",
        "accept_basic": True,  # Allow basic authentication, True or False
        "accept_digest": False,  # Allow digest authentication, True or False
        # True (default digest) or False (default basic)
        "default_to_digest": False,
        # Name of a header field that will be accepted as authorized user
        "trusted_auth_header": None,
    }
}

app = WsgiDAVApp(config)

server_args = {
    "bind_addr": (config["host"], config["port"]),
    "wsgi_app": app,
}
server = wsgi.Server(**server_args)
server.start()