import shutil
import stat
from pathlib import Path
from typing import Sequence

from clarabot_nano.server.fstx.filesystem.operation.base import AbstractIOQueueOperation


class DeleteOperation(AbstractIOQueueOperation):
    OPERATION_KEY = "DEL"

    def __init__(self, account_id: int, path: str):
        AbstractIOQueueOperation.__init__(self, account_id)
        self.path = path

    def paths(self) -> Sequence[str]:
        return (self.path,)

    def execute(self):
        path = Path(self.path)
        s = path.lstat()  # raises if target does not exist
        if stat.S_ISLNK(s.st_mode) or not stat.S_ISDIR(s.st_mode):
            path.unlink()
        else:
            shutil.rmtree(path)
