from io import StringIO
from typing import Tuple, Optional

from clarabot_nano_common.common.handler.error import NanoHandlerError
from clarabot_nano_common.common.protocol.errors import NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST
from clarabot_nano_common.common.protocol.response import NanoBaseResponse
from clarabot_nano_common.common.protocol.server import NanoServerResponse
from clarabot_nano_common.server.general.handler.base import AbstractGeneralNanoServerHandler

from clarabot_nano.common.request.server_general import AdminGetRemoteConfigRequest


class AdminGetRemoteConfigResponse(NanoBaseResponse):
    CONFIG = "config"


class GetRemoteConfigHandler(AbstractGeneralNanoServerHandler):
    REQUIRES_OWNER_IDENTITY = True
    REQUIRES_ADMIN_SESSION = True
    EXECUTION_STATE_CAN_CONFLICT = False  # cacheable and request_key are constant, no conflict is possible

    HANDLER_KEY = AdminGetRemoteConfigRequest.TYPE_KEY

    async def execute(self) -> dict:
        response = await AbstractGeneralNanoServerHandler.execute(self)
        response[NanoServerResponse.TOUCH_ADMIN_SESSION] = True
        return response

    async def _create_request_key(self, secure: bool = False) -> Tuple[bool, Optional[list], int]:
        return self._secure_request_key(False, None, 1) if secure else False, None, 1

    async def _execute_initial(self) -> dict:
        d = await AbstractGeneralNanoServerHandler._execute_initial(self)
        d[AdminGetRemoteConfigResponse.CONFIG] = self.extracted_config.remote_config
        return d

    async def _execute_part(self, part: int, s_hmac_start_part: Optional[int]) -> dict:  # pragma: no cover
        raise NanoHandlerError(NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST, "Part request is invalid", self)

    def _log_message(self) -> str:
        return "Query Nano config"

    def build_error_message(self, buf: StringIO) -> None:
        buf.write("Query Nano config")
