from typing import Tuple, Optional

from clarabot_nano.common.handler.base import NanoHandlerError, MaybeConflictNanoHandlerError
from clarabot_nano.common.protocol.errors import NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST
from clarabot_nano.common.protocol.request import NanoRequestContext
from clarabot_nano.common.request.server_fstx import AdminMkdirRequest
from clarabot_nano.server.base.config import ServerConfig
from clarabot_nano.server.base.handler.base import AbstractNanoServerHandler, ServerHandleHelper
from clarabot_nano.server.fstx.filesystem.operation.mkdir import MkdirOperation
from clarabot_nano.server.fstx.handler.base import FilesystemTransactorServerHandleHelper
from clarabot_nano.utility.path.common import normalize_validate_resolve_absolute_path
from clarabot_nano.utility.path.validate import validate_name, ValidationError


class AdminCreateDirectoryHandler(AbstractNanoServerHandler):
    """
    The owner may create directories outside of drives when browsing for a drive root.
    """

    REQUIRES_OWNER_IDENTITY = True
    REQUIRES_ADMIN_PASSWORD = True

    HANDLER_KEY = AdminMkdirRequest.TYPE_KEY

    helper: FilesystemTransactorServerHandleHelper

    def __init__(self, helper: ServerHandleHelper, extracted_config: ServerConfig, context: dict, payload: dict):
        AbstractNanoServerHandler.__init__(self, helper, extracted_config, context, payload)
        if not isinstance(self.payload.get(AdminMkdirRequest.PATH), str):
            raise NanoHandlerError(NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST, "Path is missing", self.context)
        if not isinstance(self.payload.get(AdminMkdirRequest.NAME), str):
            raise NanoHandlerError(NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST, "Name is missing", self.context)
        self.path = None
        self.name = None

    async def _create_request_key(self) -> Tuple[bool, Optional[list], int]:
        return False, None, 1

    async def _execute_initial(self) -> dict:
        d = await AbstractNanoServerHandler._execute_initial(self)
        try:
            name = self.extracted_config.normalize_remote_path(self.payload[AdminMkdirRequest.NAME])
            validate_name(name)
            self.path = normalize_validate_resolve_absolute_path(self.payload[AdminMkdirRequest.PATH]) / name
            async with self.helper.fstx_queue.wait_ready(
                MkdirOperation(self.context[NanoRequestContext.ACCOUNT_ID], self.path.as_posix())
            ) as submitter:
                # Final check before execution. This can fail if contesting operations have changed the filesystem.
                if self.path != normalize_validate_resolve_absolute_path(self.payload[AdminMkdirRequest.PATH]) / name:
                    raise ValidationError("Depending paths are contested")
                await submitter()  # TODO: timeout
        except (OSError, ValidationError) as e:
            raise MaybeConflictNanoHandlerError(
                NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST,
                f"Creating directory (admin) failed {self.payload.get(AdminMkdirRequest.PATH)}",
                self.context,
            ) from e
        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.context)

    def _log_message(self) -> str:
        return f"Make directory (admin) {self.path}"
