#
# Copyright © 2024 Neal Gompa.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.
#

""" Abstraction for running a Wayland client on kwin headless. """

from os import environ, getpid
from wlheadless.wlheadless_common import WlheadlessCommon
from wlheadless.xwayland import Xwayland

class Wlheadless:

    """
    Abstraction for running a Wayland client on kwin headless.
    """

    def __call__(self):
        return self


    def __init__(self):
        self.compositor_args = []
        self.compositor = [
            'dbus-run-session',
            'kwin_wayland',
            '--virtual',
        ]
        self.wlheadless_common = WlheadlessCommon()
        self.xwayland = Xwayland()


    def spawn_client(self, command_args):
        """Helper function to spawn the Wayland client."""
        return self.wlheadless_common.run_command(command_args)


    def spawn_xwayland(self, xserver_args = []):
        """Helper function to spawn Xwayland."""
        xserver_args.extend(['-fullscreen'])
        return self.xwayland.spawn_xwayland(xserver_args)


    def wait_compositor(self):
        """Waits for the compositor to start."""
        return self.wlheadless_common.wait_compositor()


    def run_compositor(self, compositor_args = []):
        """Helper function to spawn kwin."""
        wayland_display = 'wayland-' + format(getpid())
        environ['WAYLAND_DISPLAY'] = wayland_display
        compositor = self.compositor
        compositor.extend(self.compositor_args)
        compositor.extend(['--socket', format(wayland_display)])
        return self.wlheadless_common.run_compositor(compositor)
