#!/usr/bin/python3
"""Hidden maintenance UI. Saving requires an administrator's password."""
import os
import pwd
import subprocess
import sys
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
sys.path.insert(0, "/usr/local/lib/ekklesia-classroom")
from classroom_config import read_device_config, ui_scale

def main():
    if pwd.getpwuid(os.getuid()).pw_name != "classroom":
        sys.exit("Open this window from the classroom display session.")
    window = Gtk.Dialog(title="Classroom display size")
    window.set_default_size(440, 180)
    window.add_button("Close", Gtk.ResponseType.CANCEL)
    window.add_button("Save and apply", Gtk.ResponseType.OK)
    box = window.get_content_area()
    box.set_border_width(20)
    box.set_spacing(16)
    label = Gtk.Label(label="Display size for this room\n200% is a good starting point for a 4K TV.")
    box.add(label)
    sizes = Gtk.ComboBoxText()
    current = ui_scale(read_device_config())
    choices = [1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 3.0]
    if current not in choices:
        choices.append(current)
        choices.sort()
    for value in choices:
        sizes.append(str(value), f"{value * 100:g}%")
    sizes.set_active_id(str(current))
    box.add(sizes)
    box.add(Gtk.Label(label="Saving requires an administrator password."))
    window.show_all()
    while window.run() == Gtk.ResponseType.OK:
        selected = sizes.get_active_id()
        if float(selected) == current:
            continue
        result = subprocess.run(["pkexec", "/usr/local/bin/classroom-set-scale", selected], capture_output=True, text=True)
        if result.returncode:
            message = "No change saved. Authentication was cancelled or the setting could not be saved."
        else:
            applied = subprocess.run(["/usr/local/bin/classroom-scale"], capture_output=True, text=True)
            current = float(selected)
            message = "Display size saved and applied." if applied.returncode == 0 else "Display size saved, but applying it failed. Sign out and back in to retry."
        info = Gtk.MessageDialog(transient_for=window, modal=True, message_type=Gtk.MessageType.INFO, buttons=Gtk.ButtonsType.OK, text=message)
        info.run()
        info.destroy()
    window.destroy()

if __name__ == "__main__":
    main()
