"""Klien HTTP kecil (hanya library bawaan Python) untuk bicara dengan api.php."""
import json
import urllib.error
import urllib.parse
import urllib.request


class ApiError(Exception):
    def __init__(self, message, status=0):
        super().__init__(message)
        self.status = status


class Api:
    def __init__(self, url, key, timeout=8):
        self.url = url
        self.key = key
        self.timeout = timeout

    def call(self, action, payload=None, **params):
        query = urllib.parse.urlencode(dict(params, action=action))
        full = self.url + ("&" if "?" in self.url else "?") + query
        headers = {
            "X-API-Key": self.key,
            "User-Agent": "PCMon/1.0",
            "Accept": "application/json",
        }
        data = None
        if payload is not None:
            data = json.dumps(payload).encode("utf-8")
            headers["Content-Type"] = "application/json"
        req = urllib.request.Request(
            full, data=data, headers=headers,
            method="POST" if data is not None else "GET",
        )
        status = 200
        try:
            with urllib.request.urlopen(req, timeout=self.timeout) as resp:
                raw = resp.read()
        except urllib.error.HTTPError as exc:
            status = exc.code
            raw = exc.read()
        except Exception as exc:  # jaringan putus, DNS, timeout, dsb.
            raise ApiError("Tidak bisa terhubung ke server: %s" % exc)
        try:
            result = json.loads(raw.decode("utf-8"))
        except ValueError:
            raise ApiError("Balasan server bukan JSON (HTTP %d)" % status, status)
        if not result.get("ok"):
            raise ApiError(result.get("error", "Error tidak diketahui"), status)
        return result
