from __future__ import annotations

import stat
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Optional, Dict

from clarabot_crypto.keyring.adhoc import AdhocKeyring

from clarabot_nano.inter.job import AbstractInterNanoJob, AbstractInterNanoJobExecutor


class InterNanoCheckExecutor(AbstractInterNanoJobExecutor):
    _job: InterNanoCheckJob

    NAME_PREFIX = "CHK-"

    async def _run_custom(self, pool: ThreadPoolExecutor):
        # NOTE: no fstx lock necessary
        _, s = self.chroot.path_stat(self._job.drive_path)
        if not stat.S_ISDIR(s.st_mode):
            raise NotADirectoryError("Local copy target must be a directory")
        peek = await self._peek_remote_item(pool, self._job.remote_path)
        return peek is not None

    async def _copy_file_old_to_new(self, pool: ThreadPoolExecutor, src: Path, trg: Path) -> bool:  # pragma: no cover
        raise Exception("No old source support")


class InterNanoCheckJob(AbstractInterNanoJob):
    TYPE = "check"
    EXECUTOR_CLS = InterNanoCheckExecutor

    def __init__(
        self,
        account_id: str,  # account-id of the initiator
        room_id: str,  # room-id if the local nano
        drive_path: str,  # directory in local drive to lock during check
        remote_room_id: str,  # room-id of the remote nano
        remote_path: str,  # item in remote drive to peek for check
        room_keys: Optional[Dict[str, bytes]] = None,
        adhoc_token: Optional[str] = None,
        adhoc_kr: Optional[AdhocKeyring] = None,
    ):
        AbstractInterNanoJob.__init__(self, account_id, room_id, remote_room_id, room_keys, adhoc_token, adhoc_kr)
        self.drive_path = drive_path
        self.remote_path = remote_path

    def describe(self) -> dict:
        d = AbstractInterNanoJob.describe(self)
        d.update(
            {
                "remote_room_id": self.remote_room_id,
                "remote_path": self.remote_path,
            }
        )
        return d
