from sqlalchemy.engine import URL

from openlog.datamodel.connection.openlog_connection import Connection

MSSQL_SECURE_CONNECTION_OPTION = "secure_connection"


def get_connection_url(connection: Connection):
    query_params = {
        "driver": "ODBC Driver 18 for SQL Server"
    }

    secure_connection = False
    if connection.optional_params and MSSQL_SECURE_CONNECTION_OPTION in list(connection.optional_params.keys()):
        secure_connection = connection.optional_params[MSSQL_SECURE_CONNECTION_OPTION]

    if secure_connection:
        query_params["trusted_connection"] = "Yes"
        query_params["TrustServerCertificate"] = "Yes"
        connection_url = URL.create(
            "mssql+pyodbc",
            host=connection.host,
            database=connection.database,
            query=query_params,
        )
    else:
        query_params["authentication"] = "SqlPassword"
        query_params["TrustServerCertificate"] = "Yes"
        connection_url = URL.create(
            "mssql+pyodbc",
            username=connection.user,
            password=connection.password,
            host=connection.host,
            port=connection.port,
            database=connection.database,
            query=query_params,
        )
    return connection_url
