# retoor <retoor@molodetz.nl>

from __future__ import annotations

import xmlrpc.client
from typing import Any
from urllib.parse import quote, urlsplit, urlunsplit


class DevPlace:
    def __init__(
        self,
        base_url: str,
        api_key: str | None = None,
        username: str | None = None,
        password: str | None = None,
    ) -> None:
        self.base_url = base_url.rstrip("/")
        self.api_key = api_key
        endpoint = self.base_url + "/xmlrpc"
        if username and password:
            parts = urlsplit(self.base_url)
            credentials = f"{quote(username, safe='')}:{quote(password, safe='')}"
            endpoint = urlunsplit(
                (parts.scheme, f"{credentials}@{parts.netloc}", parts.path + "/xmlrpc", "", "")
            )
        self.proxy = xmlrpc.client.ServerProxy(endpoint, allow_none=True)

    def call(self, method: str, **params: Any) -> Any:
        if self.api_key and "api_key" not in params:
            params["api_key"] = self.api_key
        return getattr(self.proxy, method)(params)

    def methods(self) -> list[str]:
        return sorted(self.proxy.system.listMethods())

    def help(self, method: str) -> str:
        return self.proxy.system.methodHelp(method)
