#!/usr/bin/python3

import evdev
import sys
import subprocess
from evdev import InputDevice, categorize, ecodes

def main():
    try:

        # Get devices list
        devices = [evdev.InputDevice(path) for path in evdev.list_devices()]
        for device in devices:
            print(device.path, device.name, device.phys)
            if "gpio-keys" in device.name:
                break
            else:
                print("Skipping device")

        print("Device:", device)

        # Check the device: not empty, has SW_RFKILL_ALL
        if device is None:
            print("No suitable device, exiting")
            sys.exit(1)

        if "SW_RFKILL_ALL" not in str(device.capabilities(verbose=True)):
            print("No SW_RFKILL_ALL support, exiting")
            sys.exit(2)

        print("Capabilities:", device.capabilities(verbose=True))

        for event in device.read_loop():
            if event.type == ecodes.EV_SW:
                print(categorize(event))
                print("val =", event.value)
                if event.value == 0:
                    print("value is 0, toggling")
                    subprocess.call(["/bin/toggle-flight-mode.sh"], shell=True, universal_newlines=True)
                else:
                    print("value is 1, toggling again")
                    subprocess.call(["/bin/toggle-flight-mode.sh"], shell=True, universal_newlines=True)
            else:
                print("NOT A sw")

        print("Finishing")


    except Exception as e:
        print(f"An error occurred: {e}")
        exit_program()

def exit_program():
    print("Exiting the program...")
    sys.exit(0)

if __name__ == "__main__":
    main()
