__all__ = ["ArangoClient"]

from json import dumps, loads
from typing import Any, Callable, Optional, Sequence, Union

from pkg_resources import get_distribution

from arango.connection import (
    BasicConnection,
    Connection,
    JwtConnection,
    JwtSuperuserConnection,
)
from arango.database import StandardDatabase
from arango.exceptions import ServerConnectionError
from arango.http import DefaultHTTPClient, HTTPClient
from arango.resolver import (
    HostResolver,
    RandomHostResolver,
    RoundRobinHostResolver,
    SingleHostResolver,
)


class ArangoClient:
    """ArangoDB client.

    :param hosts: Host URL or list of URLs (coordinators in a cluster).
    :type hosts: str | [str]
    :param host_resolver: Host resolver. This parameter used for clusters (when
        multiple host URLs are provided). Accepted values are "roundrobin" and
        "random". Any other value defaults to round robin.
    :type host_resolver: str
    :param resolver_max_tries: Number of attempts to process an HTTP request
        before throwing a ConnectionAbortedError. Must not be lower than the
        number of hosts.
    :type resolver_max_tries: int
    :param http_client: User-defined HTTP client.
    :type http_client: arango.http.HTTPClient
    :param serializer: User-defined JSON serializer. Must be a callable
        which takes a JSON data type object as its only argument and return
        the serialized string. If not given, ``json.dumps`` is used by default.
    :type serializer: callable
    :param deserializer: User-defined JSON de-serializer. Must be a callable
        which takes a JSON serialized string as its only argument and return
        the de-serialized object. If not given, ``json.loads`` is used by
        default.
    :type deserializer: callable
    :param verify_override: Override TLS certificate verification. This will
       override the verify method of the underlying HTTP client.
       None: Do not change the verification behavior of the underlying HTTP client.
       True: Verify TLS certificate using the system CA certificates.
       False: Do not verify TLS certificate.
       str: Path to a custom CA bundle file or directory.
    :type verify_override: Union[bool, str, None]
    :param request_timeout: This is the default request timeout (in seconds)
       for http requests issued by the client if the parameter http_client is
       not secified. The default value is 60.
       None: No timeout.
       int: Timeout value in seconds.
    :type request_timeout: Any
    """

    def __init__(
        self,
        hosts: Union[str, Sequence[str]] = "http://127.0.0.1:8529",
        host_resolver: str = "roundrobin",
        resolver_max_tries: Optional[int] = None,
        http_client: Optional[HTTPClient] = None,
        serializer: Callable[..., str] = lambda x: dumps(x),
        deserializer: Callable[[str], Any] = lambda x: loads(x),
        verify_override: Union[bool, str, None] = None,
        request_timeout: Any = 60,
    ) -> None:
        if isinstance(hosts, str):
            self._hosts = [host.strip("/") for host in hosts.split(",")]
        else:
            self._hosts = [host.strip("/") for host in hosts]

        host_count = len(self._hosts)
        self._host_resolver: HostResolver

        if host_count == 1:
            self._host_resolver = SingleHostResolver(1, resolver_max_tries)
        elif host_resolver == "random":
            self._host_resolver = RandomHostResolver(host_count, resolver_max_tries)
        else:
            self._host_resolver = RoundRobinHostResolver(host_count, resolver_max_tries)

        # Initializes the http client
        self._http = http_client or DefaultHTTPClient()
        # Sets the request timeout.
        # This call can only happen AFTER initializing the http client.
        if http_client is None:
            self.request_timeout = request_timeout

        self._serializer = serializer
        self._deserializer = deserializer
        self._sessions = [self._http.create_session(h) for h in self._hosts]

        # override SSL/TLS certificate verification if provided
        if verify_override is not None:
            for session in self._sessions:
                session.verify = verify_override

    def __repr__(self) -> str:
        return f"<ArangoClient {','.join(self._hosts)}>"

    def close(self) -> None:  # pragma: no cover
        """Close HTTP sessions."""
        for session in self._sessions:
            session.close()

    @property
    def hosts(self) -> Sequence[str]:
        """Return the list of ArangoDB host URLs.

        :return: List of ArangoDB host URLs.
        :rtype: [str]
        """
        return self._hosts

    @property
    def version(self) -> str:
        """Return the client version.

        :return: Client version.
        :rtype: str
        """
        version: str = get_distribution("python-arango").version
        return version

    @property
    def request_timeout(self) -> Any:
        """Return the request timeout of the http client.

        :return: Request timeout.
        :rtype: Any
        """
        return self._http.REQUEST_TIMEOUT  # type: ignore

    # Setter for request_timeout
    @request_timeout.setter
    def request_timeout(self, value: Any) -> None:
        self._http.REQUEST_TIMEOUT = value  # type: ignore

    def db(
        self,
        name: str = "_system",
        username: str = "root",
        password: str = "",
        verify: bool = False,
        auth_method: str = "basic",
        superuser_token: Optional[str] = None,
        verify_certificate: bool = True,
    ) -> StandardDatabase:
        """Connect to an ArangoDB database and return the database API wrapper.

        :param name: Database name.
        :type name: str
        :param username: Username for basic authentication.
        :type username: str
        :param password: Password for basic authentication.
        :type password: str
        :param verify: Verify the connection by sending a test request.
        :type verify: bool
        :param auth_method: HTTP authentication method. Accepted values are
            "basic" (default) and "jwt". If set to "jwt", the token is
            refreshed automatically using ArangoDB username and password. This
            assumes that the clocks of the server and client are synchronized.
        :type auth_method: str
        :param superuser_token: User generated token for superuser access.
            If set, parameters **username**, **password** and **auth_method**
            are ignored. This token is not refreshed automatically.
        :type superuser_token: str
        :param verify_certificate: Verify TLS certificates.
        :type verify_certificate: bool
        :return: Standard database API wrapper.
        :rtype: arango.database.StandardDatabase
        :raise arango.exceptions.ServerConnectionError: If **verify** was set
            to True and the connection fails.
        """
        connection: Connection

        if superuser_token is not None:
            connection = JwtSuperuserConnection(
                hosts=self._hosts,
                host_resolver=self._host_resolver,
                sessions=self._sessions,
                db_name=name,
                http_client=self._http,
                serializer=self._serializer,
                deserializer=self._deserializer,
                superuser_token=superuser_token,
            )
        elif auth_method.lower() == "basic":
            connection = BasicConnection(
                hosts=self._hosts,
                host_resolver=self._host_resolver,
                sessions=self._sessions,
                db_name=name,
                username=username,
                password=password,
                http_client=self._http,
                serializer=self._serializer,
                deserializer=self._deserializer,
            )
        elif auth_method.lower() == "jwt":
            connection = JwtConnection(
                hosts=self._hosts,
                host_resolver=self._host_resolver,
                sessions=self._sessions,
                db_name=name,
                username=username,
                password=password,
                http_client=self._http,
                serializer=self._serializer,
                deserializer=self._deserializer,
            )
        else:
            raise ValueError(f"invalid auth_method: {auth_method}")

        if verify:
            try:
                connection.ping()
            except ServerConnectionError as err:
                raise err
            except Exception as err:
                raise ServerConnectionError(f"bad connection: {err}")

        return StandardDatabase(connection)
