import shlex
from typing import IO

from ..Logging.Logger import log, Severity
from .MachineInterface import MachineInterface
from .SSHClient import SSHClient


class SSHMachine(MachineInterface):
    def __init__(self, ssh_client: SSHClient):
        self.ssh_client = ssh_client

    def initialize(self):
        log(f"Initializing SSH machine: {self.ssh_client.host}", Severity.TRACE)
        self.ssh_client.connect()
        log(f"Connected to {self.ssh_client.host}", Severity.DEBUG)

    def check_if_file_exists(self, file_path: str) -> bool:
        return self.ssh_client.file_exists(file_path)

    def read_file(self, file_path: str) -> bytes:
        return self.ssh_client.read_file(file_path)

    def write_file(self, file_path: str, data: bytes) -> None:
        self.ssh_client.write_file(file_path, data)

    def delete(self, file_path: str):
        self.ssh_client.execute_command(shlex.join(['rm', '-rf', file_path]))

    def move(self, source_file: str, destination_file: str):
        self.ssh_client.execute_command(shlex.join(['mv', source_file, shlex.quote(destination_file)]))

    def mkdir(self, dir_path) -> None:
        self.ssh_client.execute_command(shlex.join(["mkdir", "-p", dir_path]))

    def execute_shell_command(self, command: str, *args: str, non_blocking = False) ->  tuple[str, str, int]:
        argv_str = f'{command} {shlex.join(args)}'
        return self.ssh_client.execute_command(argv_str, non_blocking=non_blocking)

    def execute_shell_command_live(self, command: str, *args: str) ->  tuple[IO, IO, IO]:
        argv_str = f'{command} {shlex.join(args)}'
        return self.ssh_client.execute_command_live(argv_str)

    def get_hostname(self) -> str:
        return self.ssh_client.host

    def get_hostname_short(self) -> str:
        return self.ssh_client.host.split('.')[0]
