#!/usr/bin/env python3
import gi
import subprocess

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk

class XRandrGUI(Gtk.Window):
    def __init__(self):
        super().__init__()

        header = Gtk.HeaderBar(title="Xrandr GUI")
        header.set_subtitle("Select screen resolution")
        header.set_show_close_button(True)
        self.set_titlebar(header)
        
        self.set_default_size(350, 350)
        self.set_position(Gtk.WindowPosition.CENTER)
        self.set_icon_from_file("/usr/share/icons/hicolor/48x48/apps/xrandr-gui.png")

        # Fetch resolutions
        self.resolutions = self.get_resolutions()
        self.current_res = self.get_current_resolution()

        # Main vertical box
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
        vbox.set_border_width(10)

        # Status label
        self.status_label = Gtk.Label(label=f"Current resolution: {self.current_res}")
        self.status_label.set_xalign(0)
        vbox.pack_start(self.status_label, False, False, 0)

        # ListBox for resolutions
        self.listbox = Gtk.ListBox()
        for res in self.resolutions:
            row = Gtk.ListBoxRow()
            label = Gtk.Label(label=res, xalign=0)
            row.add(label)
            self.listbox.add(row)
        self.listbox.connect("row-selected", self.on_row_selected)
        vbox.pack_start(self.listbox, True, True, 0)

        # Buttons box
        button_box = Gtk.Box(spacing=10)
        apply_button = Gtk.Button.new_from_icon_name("emblem-ok", Gtk.IconSize.BUTTON)
        apply_button.set_label("Apply")
        apply_button.set_always_show_image(True)
        apply_button.connect("clicked", self.apply_resolution)
        
        cancel_button = Gtk.Button.new_from_icon_name("process-stop", Gtk.IconSize.BUTTON)
        cancel_button.set_label("Cancel")
        cancel_button.set_always_show_image(True)
        cancel_button.connect("clicked", self.on_cancel)

        button_box.pack_start(apply_button, True, True, 0)
        button_box.pack_start(cancel_button, True, True, 0)
        vbox.pack_start(button_box, False, False, 0)

        self.add(vbox)
        self.show_all()

    def get_resolutions(self):
        try:
            xrandr_output = subprocess.check_output(["xrandr"], stderr=subprocess.STDOUT).decode("utf-8")
            resolutions = []
            for line in xrandr_output.splitlines():
                if "x" in line and not "disconnected" in line:
                    resolution = line.split()[0]
                    if resolution not in resolutions:
                        resolutions.append(resolution)
            return resolutions
        except subprocess.CalledProcessError as e:
            print(f"Error running xrandr: {e}")
            return []

    def get_current_resolution(self):
        try:
            output = subprocess.check_output(["xrandr"], stderr=subprocess.STDOUT).decode("utf-8")
            for line in output.splitlines():
                if "*" in line:
                    return line.strip().split()[0]
            return "Unknown"
        except subprocess.CalledProcessError as e:
            print(f"Error running xrandr: {e}")
            return "Unknown"

    def on_row_selected(self, listbox, row):
        if row:
            selected = row.get_child().get_text()
            self.status_label.set_text(f"Selected: {selected}")

    def apply_resolution(self, widget):
        row = self.listbox.get_selected_row()
        if row:
            resolution = row.get_child().get_text()
            print(f"Applying resolution: {resolution}")
            subprocess.run(["xrandr", "-s", resolution])
        Gtk.main_quit()

    def on_cancel(self, widget):
        Gtk.main_quit()

def main():
    window = XRandrGUI()
    window.connect("destroy", Gtk.main_quit)
    Gtk.main()

if __name__ == "__main__":
    main()

