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,
    NANO_REQUEST_ERROR_HANDLER_DENIED,
)
from clarabot_nano_common.common.protocol.server import NanoServerResponse
from clarabot_nano_common.server.general.handler.base import AbstractGeneralNanoServerHandler
from clarabot_nano_common.utility.serialize import msgpack_dumps, msgpack_loads

from clarabot_nano.common.core.message import MSG_TYPE_REQUEST_CONFIG_UPDATE


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

    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:
        reply = await self.helper.core_requester.request(
            [MSG_TYPE_REQUEST_CONFIG_UPDATE, msgpack_dumps(self._create_config_update_request())]
        )
        if len(reply) == 1:
            response = msgpack_loads(reply[0])
            if bool(response.get("ok")):
                return await AbstractGeneralNanoServerHandler._execute_initial(self)
            if response.get("info") == "sensitive":
                raise NanoHandlerError(NANO_REQUEST_ERROR_HANDLER_DENIED, "Denied", self)
        raise NanoHandlerError(NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST, "Failed", self)

    def _create_config_update_request(self) -> dict:
        raise NotImplementedError()

    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:
        raise NotImplementedError()

    def build_error_message(self, buf: StringIO) -> None:
        buf.write(self._log_message())
