import json
import time
from threading import Thread

import dbus
import dbus.service

from session import Session


class RWAService(dbus.service.Object):
    def __init__(self):
        self.bus = dbus.SessionBus()
        name = dbus.service.BusName("org.ArcticaProject.RWA", bus=self.bus)

        self.update_service_running = False
        self.sessions = {}
        super().__init__(name, "/RWA")

    @dbus.service.method("org.ArcticaProject.RWA", out_signature="s")
    def start(self):
        """Start a new remote session."""
        # Start session
        session = Session()

        # Add session to sessions list
        self.sessions[session.pid] = session

        # Start session update service
        self._ensure_update_service()

        return json.dumps(session.client_meta)

    @dbus.service.method("org.ArcticaProject.RWA", in_signature="i")
    def stop(self, pid: int):
        """Stop a remote session."""
        session = self.sessions[pid]
        session.stop()

    def _ensure_update_service(self):
        """Start session update thread if it isn't already running."""
        if not self.update_service_running:
            self.update_thread = Thread(target=self._update_sessions)
            self.update_thread.start()

    def _update_sessions(self):
        """Go through all running sessions and update their status.

        Things that this function will do:
        - Check if VNC is still running
        - Kill websockify if VNC process is dead
        """
        while len(self.sessions.values()) > 0:
            for session in list(self.sessions.values()):
                print(f"Session #{session.pid}")

                # Check if VNC process is still running
                running = session.vnc_process_running
                if running:
                    print("Session is running")
                else:
                    print("Session is dead.")

                    session.stop()
                    del self.sessions[session.pid]

            time.sleep(2)

        self.update_service_running = False
        # TODO Probably kill daemon here (quit main loop)


if __name__ == "__main__":
    import dbus.mainloop.glib
    from gi.repository import GLib

    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

    loop = GLib.MainLoop()
    object = RWAService()
    loop.run()
