import logging
import os
import time
from typing import Sequence, Optional

from clarabot_nano.common.filesystem.operation.base import AbstractIOQueueOperation

logger = logging.getLogger(__name__)


class ReplaceOperation(AbstractIOQueueOperation):
    OPERATION_KEY = "REP"

    def __init__(self, account_id: int, src: str, dst: str, mtime_ns: Optional[int] = None):
        AbstractIOQueueOperation.__init__(self, account_id)
        self.src = src
        self.dst = dst
        self.mtime_ns = mtime_ns

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

    def execute(self):
        if self.mtime_ns is not None:
            try:
                os.utime(self.src, ns=(time.time_ns(), self.mtime_ns))
            except OSError:
                logger.exception("Failed to set mtime of file before replace")
        os.replace(self.src, self.dst)
