import stat
from typing import Tuple, Optional

from clarabot_nano.common.handler.base import NanoHandlerError
from clarabot_nano.common.protocol.errors import (
    NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST,
    NANO_REQUEST_ERROR_HANDLER_TARGET_NOT_FOUND,
)
from clarabot_nano.common.protocol.response import NanoBaseResponse
from clarabot_nano.common.request.server_general import NanoFilesystemPeekRequest
from clarabot_nano.server.base.config import ServerConfig
from clarabot_nano.server.base.handler.base import ServerHandleHelper
from clarabot_nano.server.base.handler.filesystem.base import AbstractFileSystemHandler
from clarabot_nano.utility.path.validate import ValidationError


class NanoFilesystemPeekResponse(NanoBaseResponse):
    PEEK = "pk"  # similar data to listing if path exists


class PeekFileSystemHandler(AbstractFileSystemHandler):
    REJECTS_ANONYMOUS_IDENTITY = False  # Further authorization is by room membership and group flags.

    HANDLER_KEY = NanoFilesystemPeekRequest.TYPE_KEY

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

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

    async def _execute_initial(self) -> dict:
        try:
            paths, s = self.chroot.paths_stat(self.payload[NanoFilesystemPeekRequest.PATH])
        except (OSError, ValidationError):
            raise NanoHandlerError(NANO_REQUEST_ERROR_HANDLER_TARGET_NOT_FOUND, "Path is invalid", self.context)
        if len(paths) <= 1:  # Disallow peeking the drive-root.
            raise NanoHandlerError(NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST, "Path is invalid", self.context)
        self.path = paths[-1][0]
        # NOTE: we return the name because it *may* be different than in the request path for case-insensitive FS.
        peek = {"name": self.path.name, "mtime": s.st_mtime}
        if stat.S_ISDIR(s.st_mode):
            pass
        else:
            peek["size"] = s.st_size
        d = await AbstractFileSystemHandler._execute_initial(self)
        d[NanoFilesystemPeekResponse.PEEK] = peek
        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"Peek {self.path}"
