from io import StringIO
from typing import Tuple, Optional

from clarabot_nano_common.common.error import log_escape_str
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.response import NanoBaseResponse
from clarabot_nano_common.server.base.config import ServerConfig
from clarabot_nano_common.server.base.handler.base import ServerHandleHelper

from clarabot_nano.common.request.server_fstx import NanoFilesystemLockGetRequest
from clarabot_nano.server.fstx.handler.base import AbstractFilesystemTransactorNanoHandler


class NanoFilesystemLockGetResponse(NanoBaseResponse):
    TOKEN = "t"


class GetLockSystemHandler(AbstractFilesystemTransactorNanoHandler):
    EXECUTION_STATE_CAN_CONFLICT = False  # cacheable and request_key are constant, no conflict is possible
    ALLOW_INTERNAL_REQUEST_EXECUTION = True

    HANDLER_KEY = NanoFilesystemLockGetRequest.TYPE_KEY

    def __init__(self, helper: ServerHandleHelper, extracted_config: ServerConfig, context: dict, payload: dict):
        AbstractFilesystemTransactorNanoHandler.__init__(self, helper, extracted_config, context, payload)
        if not isinstance(self.payload.get(NanoFilesystemLockGetRequest.PATH), str):
            raise NanoHandlerError(NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST, "Missing path", self)
        if not self.can_write_drive():
            raise NanoHandlerError(NANO_REQUEST_ERROR_HANDLER_DENIED, "No permission", self)
        self.path = None

    async def _execute_internal(self) -> dict:
        paths, s = self.resolve_chroot_paths_stat(self.chroot, self.payload[NanoFilesystemLockGetRequest.PATH])
        self.path = paths[-1][0]
        return {NanoFilesystemLockGetResponse.TOKEN: self.helper.fstx_queue.get_ex_lock_token(self.path.as_posix())}

    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 AbstractFilesystemTransactorNanoHandler._execute_initial(self)
        d.update(await self._execute_internal())
        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"Get lock {log_escape_str(self.path)}"

    def build_error_message(self, buf: StringIO) -> None:
        buf.write("Get lock ")
        buf.write(log_escape_str(self.payload.get(NanoFilesystemLockGetRequest.PATH)))
        buf.write(" in ")
        buf.write(log_escape_str(self.get_drive_root_for_error_message()))
