#!/usr/bin/env python3

import time
import subprocess

import gi, signal
gi.require_version('Gio', '2.0')
gi.require_version('AyatanaAppIndicator3', '0.1')

from gi.repository import Gio
from gi.repository import AyatanaAppIndicator3 as AppIndicator3
from gi.repository import Gtk


def check_alive(extension_name: str):

    cmd = ['gnome-extensions', 'info', extension_name]

    result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

    #print(result)
    out = result.stdout.decode().split('\n')
    #print(f'---- STDOUT: {out}')

    if out[0] != extension_name:
        print('Ext not present')
        return False

    for entry in out:
        kv = entry.strip().split(':', 1)
        #print(f'{len(kv)}: {kv}')
        if len(kv) >= 2:
            k, v = kv
            #print(f'key {k} = {v}')
            if k.strip() == 'State' and v.strip() == 'ENABLED':
                #print('Found ENA')
                return True

    return False

def set_power_profile(new_mode: str):
    # Set the ActiveProfile property to "balanced", "power-saver", or "performance"
    cmds = ['powerprofilesctl', 'set', new_mode]
    result = subprocess.run(cmds, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    msg = result.stdout.decode()
    print(msg)

def main():

    # Set the ActiveProfile property to "balanced", "power-saver", or "performance"
    set_power_profile('power-saver')

    extension_name = 'appindicatorsupport@rgcjonas.gmail.com'
    while not check_alive(extension_name=extension_name):
        print('Gnome Extension not ready, waiting 10 sec')
        time.sleep(10)

    print('Gnome Extension ready, starting up...')

    indicator = AppIndicator3.Indicator.new(
                "Sleep Inhibitor", "caffeine", AppIndicator3.IndicatorCategory.APPLICATION_STATUS
                )
    indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE)


    bus = Gio.bus_get_sync(Gio.BusType.SESSION)
    proxy = Gio.DBusProxy.new_sync(bus, 0, None,
        'org.gnome.SessionManager', '/org/gnome/SessionManager',
        'org.gnome.SessionManager', None)

    cookie = proxy.Inhibit('(susu)', 'BSH Py script', 0, 'reason here', 12)
    print(f"Inhibited with cookie {cookie}. Press Ctrl+C to release.")

    menu = Gtk.Menu()
    quit_item = Gtk.MenuItem(label="Quit")
    quit_item.connect("activate", Gtk.main_quit)
    menu.append(quit_item)
    menu.show_all()
    indicator.set_menu(menu)

    Gtk.main()

    # When process exits, GNOME automatically removes the inhibitor

if __name__ == "__main__":
    main()
