from io import StringIO
from typing import Tuple, Optional

from clarabot_crypto.group_config.block import GroupConfigBlockMemberFlags
from clarabot_nano_common.common.error import maybe_rad32
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.request import NanoRequestContext
from clarabot_nano_common.common.protocol.response import NanoBaseResponse
from clarabot_nano_common.utility.algorithm import dict_nested_get

from clarabot_nano.common.request.gateway import NanoCountAdhocTokensRequest
from clarabot_nano.gateway.config import GatewayConfig
from clarabot_nano.gateway.handler.filesystem import AbstractFileSystemGatewayHandler
from clarabot_nano.gateway.state.gateway import GatewayState


class CountAdhocTokensResponse(NanoBaseResponse):
    COUNT = "count"


class CountAdhocTokensHandler(AbstractFileSystemGatewayHandler):
    EXECUTION_STATE_CAN_CONFLICT = False  # cacheable and request_key are constant, no conflict is possible

    HANDLER_KEY = NanoCountAdhocTokensRequest.TYPE_KEY

    def __init__(self, helper: GatewayState, extracted_config: GatewayConfig, context: dict, payload: dict):
        AbstractFileSystemGatewayHandler.__init__(self, helper, extracted_config, context, payload)
        if not self.context.get(NanoRequestContext.ROOM):
            raise NanoHandlerError(NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST, "Room is missing", self)
        if self.context[NanoRequestContext.OWNER_ACCOUNT_ID] == self.context[NanoRequestContext.ACCOUNT_ID]:
            pass  # owner may always count adhoc tokens
        else:
            # check if member is active and administrator
            config_member_flags = self.context[NanoRequestContext.ROOM][NanoRequestContext.ROOM_CONFIG_MEMBER]
            if (
                not config_member_flags
                or not (config_member_flags & GroupConfigBlockMemberFlags.ACTIVE)
                or not (config_member_flags & GroupConfigBlockMemberFlags.ADMINISTRATOR)
            ):
                raise NanoHandlerError(NANO_REQUEST_ERROR_HANDLER_DENIED, "No permission", self)
        # these will be saved for logging
        self.room_id = None

    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:
        self.room_id = dict_nested_get(self.context, NanoRequestContext.ROOM, NanoRequestContext.ROOM_ID)
        tokens = await self.helper.adhoc_db.count_by_room(self.room_id)
        d = await AbstractFileSystemGatewayHandler._execute_initial(self)
        d[CountAdhocTokensResponse.COUNT] = tokens
        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 f"Count adhoc-tokens for room {maybe_rad32(self.room_id)}"

    def build_error_message(self, buf: StringIO) -> None:
        buf.write("Count adhoc-tokens for room ")
        try:
            room_id = dict_nested_get(self.context, NanoRequestContext.ROOM, NanoRequestContext.ROOM_ID)
        except KeyError:
            pass
        else:
            buf.write(maybe_rad32(room_id))
