from pathlib import Path

from PIL import Image
from pygelf.gelf import os

from test_automation_suite.utility.cmd import run_cmd


class ScreenshotError(Exception):
    def __init__(self) -> None:
        super().__init__("Failed to take a screenshot")


def _get_screenshot_cmds() -> list[str]:
    # use different tools if we are on wayland
    if os.getenv("XDG_SESSION_TYPE") == "wayland":
        return [
            "/usr/bin/spectacle --background --fullscreen --output ",
            "/usr/bin/grim ",
            "/usr/bin/flameshot full --path ",
        ]
    return [
        "/usr/bin/scrot ",
        "/usr/bin/xfce4-screenshooter --fullscreen --save ",
        "/usr/bin/gnome-screenshot --file ",
    ]


def take_screenshot(screenshot_location: Path) -> bool:
    return any(run_cmd(f"{cmd} {screenshot_location}").success for cmd in _get_screenshot_cmds())


def is_screenshot_all_black(screenshot_location: Path) -> bool:
    with Image.open(screenshot_location) as screenshot:
        return screenshot.getbbox() is None


def is_screen_all_black(screenshot_location: Path) -> bool:
    if not take_screenshot(screenshot_location):
        raise ScreenshotError
    is_all_black = is_screenshot_all_black(screenshot_location)
    screenshot_location.unlink()
    return is_all_black
