import asyncio
import stat
from pathlib import Path
from typing import Tuple, Optional, List, Union

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.protocol.response import NanoBaseResponse
from clarabot_nano.common.request.server_general import AdminGetListingRequest
from clarabot_nano.server.base.config import ServerConfig
from clarabot_nano.server.base.handler.base import AbstractNanoServerHandler, ServerHandleHelper
from clarabot_nano.server.general.handler.filesystem.utility import file_stat, list_directory, ls_entry_size
from clarabot_nano.utility.path.common import normalize_validate_absolute_path
from clarabot_nano.utility.path.root import get_root_paths
from clarabot_nano.utility.path.validate import ValidationError
from clarabot_nano.utility.serialize import msgpack_dumps


class AdminGetListingResponse(NanoBaseResponse):
    LISTING = "ls"


class GetListingHandler(AbstractNanoServerHandler):
    REQUIRES_OWNER_IDENTITY = True
    REQUIRES_ADMIN_PASSWORD = True

    HANDLER_KEY = AdminGetListingRequest.TYPE_KEY

    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(AdminGetListingRequest.PATH), str):
            raise NanoHandlerError(NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST, "Path is missing", self.context)
        self.path: Union[str, Path] = None
        self.ls: List[List[dict]] = None

    async def _create_request_key(self) -> Tuple[bool, Optional[list], int]:
        if not self.payload[AdminGetListingRequest.PATH]:
            # Empty path means to return the valid path-roots and locations to start from.
            if self.path is None:
                self.path = "path-roots"
                # NOTE: Not using threads for the root listing. These are either a constant value (for posix) or
                # they require COM from pywin32 which would need to be initialised for the calling thread. This
                # is a very rarely used API call and branch, so fixing the thread-execution is not worth it.
                root_paths = get_root_paths()
                # root_paths = await asyncio.get_event_loop().run_in_executor(self.helper.pool, get_root_paths)
                ls = [{"name": name} for name in root_paths]
                self.ls = self._approximate_part_slicing(ls, lambda item: len(msgpack_dumps(item)), 16)
            return False, [self.HANDLER_KEY, 0, "", ""], len(self.ls)
        # The path is specified, try to list it.
        try:
            path = Path(normalize_validate_absolute_path(self.payload[AdminGetListingRequest.PATH]))
            s = await asyncio.get_event_loop().run_in_executor(self.helper.pool, file_stat, path)
        except (OSError, ValidationError):
            raise MaybeConflictNanoHandlerError(NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST, "Path is invalid", self.context)
        if self.path is None:  # pre-execution
            self.path = path
            if stat.S_ISDIR(s.st_mode):
                try:
                    ls = await asyncio.get_event_loop().run_in_executor(
                        self.helper.pool, list_directory, self.path.iterdir, True
                    )
                except (OSError, ValidationError) as e:  # pragma: no cover; cannot simulate this
                    raise MaybeConflictNanoHandlerError(
                        NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST, "Directory listing failed", self.context
                    ) from e
                self.ls = self._approximate_part_slicing(ls, ls_entry_size, 16)
            else:
                raise NanoHandlerError(NANO_REQUEST_ERROR_HANDLER_BAD_REQUEST, "Path is not a directory", self.context)
        path_parent, _, path_name = path.as_posix().rpartition("/")
        return False, [self.HANDLER_KEY, s.st_ino, path_name, path_parent], len(self.ls)

    async def _execute_initial(self) -> dict:
        d = await AbstractNanoServerHandler._execute_initial(self)
        d[AdminGetListingResponse.LISTING] = self.ls[0]
        return d

    async def _execute_part(self, part: int, s_hmac_start_part: Optional[int]) -> dict:
        d = await AbstractNanoServerHandler._execute_part(self, part, s_hmac_start_part)
        # NOTE: we cannot s_hmac the listing because it is volatile... no real benefit for p2p encryption anyways
        d[AdminGetListingResponse.LISTING] = self.ls[part]
        return d

    def _log_message(self) -> str:
        if part := self.context.get(NanoRequestContext.PART):
            return f"Admin-list {self.path} part {part}"
        return f"Admin-list {self.path}"
