from io import StringIO
from typing import Optional

from clarabot_nano_common.common.error import AbstractAccessLoggableError, build_log_identity


class GatewayRequestProcessingError(AbstractAccessLoggableError):
    @classmethod
    def format_message(
        cls,
        error_code: int,
        message: str,
        account_id: Optional[int] = None,
        maybe_account: bool = False,
        ip_address: Optional[str] = None,
    ) -> str:
        buf = StringIO()
        if account_id is None:
            pass  # If identity is missing the request processing has failed for server fields.
        else:
            build_log_identity(buf, account_id, maybe_account=maybe_account, ip_address=ip_address)
        # subject
        buf.write(str(error_code))
        buf.write(" ")
        buf.write(message)
        return buf.getvalue()

    def __init__(
        self,
        error_code: int,
        message: str,
        account_id: Optional[int] = None,
        maybe_account: bool = False,
        ip_address: Optional[str] = None,
    ):
        AbstractAccessLoggableError.__init__(
            self, error_code, self.format_message(error_code, message, account_id, maybe_account, ip_address)
        )
