import os
import gi
import platform
import subprocess
import psutil  # To fetch memory information
import getpass  # To fetch the Linux username
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk

class LinuxInfoDialog(Gtk.Dialog):
    def __init__(self, parent=None):
        super().__init__(title="About Linux", transient_for=parent, flags=0)
        self.set_default_size(400, 300)
        self.set_resizable(False)  # Adjust size to fit content snugly
        self.set_border_width(5)  # Reduce padding

        # Get real kernel version
        kernel_version = platform.uname().release

        # Get Xfce version
        xfce_version = self.get_xfce_version()

        # Get Linux distribution information
        os_info = self.get_os_info()

        # Get memory usage
        memory_info = self.get_memory_info()

        # Get Linux username
        username = getpass.getuser()

        # Get Window Manager name
        window_manager = self.get_window_manager()

        # Dialog layout
        box = self.get_content_area()

        # Banner Image (loading directly from pixmaps folder)
        banner = self.load_banner_from_pixmaps()
        if banner:
            box.pack_start(banner, expand=False, fill=False, padding=0)
        else:
            placeholder_label = Gtk.Label(label="(Banner image could not be loaded)")
            box.pack_start(placeholder_label, expand=False, fill=False, padding=0)

        # System information
        info_label = Gtk.Label(label=(
            f"Linux Version: {os_info}\n"
            f"Kernel: {kernel_version}\n"
            f"Desktop Environment: Xfce {xfce_version}\n"
            f"Window Manager: {window_manager}"
        ))
        info_label.set_justify(Gtk.Justification.LEFT)  # Align text to the left
        info_label.set_margin_top(10)
        box.pack_start(info_label, expand=True, fill=True, padding=10)

        # Add license information here (above the username)
        license_label = Gtk.Label(label="This product is licensed under the terms of the (GNU License) to:")
        license_label.set_justify(Gtk.Justification.LEFT)
        license_label.set_margin_top(10)
        box.pack_start(license_label, expand=True, fill=True, padding=5)

        # Create a new box to align the username label to the left
        username_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0)
        username_label = Gtk.Label(label=f"	User: {username}")
        username_box.pack_start(username_label, expand=False, fill=False, padding=0)  # Aligns to left by default
        box.pack_start(username_box, expand=True, fill=True, padding=5)

        # Horizontal Separator Bar
        separator = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
        box.pack_start(separator, expand=False, fill=True, padding=15)  # Increased padding here for space

        # Memory information below the separator
        memory_label = Gtk.Label(label=f"Physical Memory Available to Linux: {memory_info}")
        memory_label.set_justify(Gtk.Justification.CENTER)
        memory_label.set_margin_top(10)
        box.pack_start(memory_label, expand=True, fill=True, padding=10)

        # Buttons
        self.add_button("OK", Gtk.ResponseType.OK)
        
        self.show_all()

    def load_banner_from_pixmaps(self):
        # Modify this path to the actual location of your banner in the pixmaps directory
        pixmaps_path = os.path.expanduser("/usr/share/pixmaps/")
        banner_path = os.path.join(pixmaps_path, "winver-xp-banner.png")

        # Check if the banner exists in the specified directory
        if os.path.exists(banner_path):
            try:
                return Gtk.Image.new_from_file(banner_path)
            except Exception as e:
                print(f"Error loading banner image from pixmaps: {e}")
        else:
            print(f"Banner image not found at: {banner_path}")
        
        return None

    def get_xfce_version(self):
        try:
            # Run xfce4-session --version and capture output
            result = subprocess.run(
                ["xfce4-session", "--version"],
                capture_output=True,
                text=True,
                check=True
            )
            # Extract the version from the output
            output = result.stdout.strip()
            for line in output.split("\n"):
                if "xfce4-session" in line.lower():
                    # Example output: "xfce4-session 4.16.0 (Xfce 4.16)"
                    version = line.split()[-1]  # Get the last word
                    version = version.rstrip(')')  # Strip ')' from the right side
                    return version
        except Exception as e:
            print(f"Error detecting Xfce version: {e}")
            return "Unknown"
        return "Unknown"

    def get_os_info(self):
        try:
            with open("/etc/os-release", "r") as f:
                os_data = {}
                for line in f:
                    if "=" in line:
                        key, value = line.strip().split("=", 1)
                        os_data[key] = value.strip('"')
                # Use PRETTY_NAME if available, otherwise fallback to NAME + VERSION
                return os_data.get("PRETTY_NAME", f"{os_data.get('NAME', 'Unknown')} {os_data.get('VERSION', '')}")
        except Exception as e:
            print(f"Error retrieving OS info: {e}")
            return "Unknown"

    def get_memory_info(self):
        try:
            mem = psutil.virtual_memory()
            used_mem = mem.used // (1024 * 1024)  # Convert to MB
            total_mem = mem.total // (1024 * 1024)  # Convert to MB
            return f"{used_mem} MB / {total_mem} MB"
        except Exception as e:
            print(f"Error retrieving memory information: {e}")
            return "Unknown"

    def get_window_manager(self):
        try:
            # Look for the window manager process by searching for common window manager names
            window_managers = ["xfwm4", "openbox", "i3", "kwin", "metacity", "compiz", "awesome"]
            for wm in window_managers:
                if wm in (p.name() for p in psutil.process_iter()):
                    return wm
            return "Unknown"
        except Exception as e:
            print(f"Error detecting window manager: {e}")
            return "Unknown"

# Application run
def main():
    win = Gtk.Window(title="Linux Info")
    win.set_default_size(200, 100)
    win.connect("destroy", Gtk.main_quit)

    dialog = LinuxInfoDialog(parent=win)
    dialog.run()
    dialog.destroy()

if __name__ == "__main__":
    main()
