import logging
from io import StringIO
from typing import Tuple, Optional

from clarabot_nano_common.common.error import maybe_rad32
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 ListInterNanoJobsRequest
from clarabot_nano.gateway.config import GatewayConfig
from clarabot_nano.gateway.handler.inter_nano_job.base import AbstractInterNanoJobHandler
from clarabot_nano.gateway.state.gateway import GatewayState
from clarabot_nano.inter.job import AbstractInterNanoJobQueue


class ListInterNanoJobsResponse(NanoBaseResponse):
    JOBS = "jobs"


class ListInterNanoJobsHandler(AbstractInterNanoJobHandler):
    EXECUTION_STATE_CAN_CONFLICT = False  # cacheable and request_key are constant, no conflict is possible
    SUCCESS_LOG_LEVEL = logging.DEBUG  # do not log this normally to avoid spam

    HANDLER_KEY = ListInterNanoJobsRequest.TYPE_KEY

    def __init__(self, helper: GatewayState, extracted_config: GatewayConfig, context: dict, payload: dict):
        AbstractInterNanoJobHandler.__init__(self, helper, extracted_config, context, payload)
        # 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)
        ijq: AbstractInterNanoJobQueue = self.helper.inter_job_queue
        # NOTE: Listing the jobs of other rooms as well can help resolve a very long or stuck processing, but
        # unfortunately due to security barriers, only the owner can see all the jobs. All admins must be limited
        # to the current room they are admins in. Paths from other drives may contain sensitive information.
        jobs = await ijq.list(
            None
            if self.context[NanoRequestContext.OWNER_ACCOUNT_ID] == self.context[NanoRequestContext.ACCOUNT_ID]
            else self.room_id
        )
        d = await AbstractInterNanoJobHandler._execute_initial(self)
        d[ListInterNanoJobsResponse.JOBS] = jobs
        return d

    def _log_message(self) -> str:
        return f"List inter-nano jobs for room {maybe_rad32(self.room_id)}"

    def build_error_message(self, buf: StringIO) -> None:
        buf.write("List inter-nano jobs 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))
