"""HTTP client errors"""

from nilmdb.utils.printf import sprintf


class Error(Exception):
    """Base exception for both ClientError and ServerError responses"""
    def __init__(self,
                 status="Unspecified error",
                 message=None,
                 url=None,
                 traceback=None):
        super().__init__(status)
        self.status = status     # e.g. "400 Bad Request"
        self.message = message   # textual message from the server
        self.url = url           # URL we were requesting
        self.traceback = traceback  # server traceback, if available

    def _format_error(self, show_url):
        s = sprintf("[%s]", self.status)
        if self.message:
            s += sprintf(" %s", self.message)
        if show_url and self.url:
            s += sprintf(" (%s)", self.url)
        if self.traceback:
            s += sprintf("\nServer traceback:\n%s", self.traceback)
        return s

    def __str__(self):
        return self._format_error(show_url=False)

    def __repr__(self):
        return self._format_error(show_url=True)


class ClientError(Error):
    pass


class ServerError(Error):
    pass
