import json

from django.core.handlers.wsgi import WSGIRequest
from django.http import HttpResponse

from config import (ALLOW_NEW_USERS, DEBUG, ENABLED_APPLICATIONS,
                    MAX_SESSION_LENGTH, MAX_SESSION_TIMEOUT, tCOMMON_TOKEN,
                    tCOMMON_URL_INTERNAL, tCOMMON_URL_PUBLIC)
from tcommon.settings import VERSION


def initialize(request: WSGIRequest) -> HttpResponse:
    if request.GET.get("token") != tCOMMON_TOKEN:
        return HttpResponse(
            json.dumps({
                "success": False
            }),
            content_type="application/json",
            status=401
        )

    resp = {
        "debug": DEBUG,
        "version": list(VERSION),
        "version_str": ".".join([str(i) for i in VERSION]),
        "new_users": ALLOW_NEW_USERS,
        "session_timeout": MAX_SESSION_TIMEOUT,
        "session_length": MAX_SESSION_LENGTH,
        "success": True,
        "services": {
            "common": {
                "url": {
                    "pub": tCOMMON_URL_PUBLIC,
                    "int": tCOMMON_URL_INTERNAL
                },
                "token": tCOMMON_TOKEN
            }
        }
    }

    for service in [
        "auth", "message"
    ]:
        if service in ENABLED_APPLICATIONS and isinstance(s := ENABLED_APPLICATIONS[service], tuple):
            resp["services"][service] = {
                "url": {
                    "pub": s[2],
                    "int": s[1],
                },
                "token": s[0]
            }
        else:
            resp["services"][service] = None

    return HttpResponse(
        json.dumps(resp),
        content_type="application/json"
    )
