#
# Copyright (C) 2019-Present A-Team Digital Solutions
#

import os
from pathlib import Path
from gi.repository import (
    GLib,
    Vte
)
BASE = str(
    Path(__file__).resolve().parent.parent
)

class ResourceMonitor:
    def __init__(self, terminal_manager):
        self.terminal = None
        self.running = False
        self.terminal_manager = terminal_manager
    def attach(self, terminal):
        self.terminal = terminal
        self.terminal.connect(
            "child-exited",
            self.on_child_exited
        )
    def get_command(self):
        if (
            self.terminal_manager.ssh_connected and
            self.terminal_manager.remote_user and
            self.terminal_manager.remote_host
        ):
            return [
                "ssh",
                "-t",
                "-p",
                str(self.terminal_manager.remote_port),
                f"{self.terminal_manager.remote_user}@{self.terminal_manager.remote_host}",
                "btop",
            ]
        return [
            "bash",
            os.path.join(BASE, "scripts", "resource_monitor.sh"),
        ]
    def get_workdir(self):
        return BASE
    def start(self):
        if self.terminal is None:
            return
        if self.running:
            return
        print("Starting Resource Monitor")
        self.running = True
        self.terminal.spawn_async(
            Vte.PtyFlags.DEFAULT | Vte.PtyFlags.NO_LASTLOG,
            self.get_workdir(),
            self.get_command(),
            None,
            GLib.SpawnFlags.DEFAULT,
            None,
            None,
            -1,
            None,
            None
        )
    def restart(self):
        if self.terminal is None:
            return
        self.terminal.reset(True, True)
        self.running = False
        self.start()
    def on_child_exited(self, terminal, status):
        print("Resource Monitor Exited")
        self.running = False
        GLib.timeout_add(
            500,
            self._restart_timeout
        )
    def _restart_timeout(self):
        self.start()
        return False
