#!/usr/bin/python3

from evdev import ecodes, InputDevice
from time import time
from select import select
import os
import sys
import evdev


def main(args):
    powerkeyname = '30370000.snvs:snvs-powerkey'

    path = [path for path in evdev.list_devices() if evdev.InputDevice(path).name == powerkeyname]
    foundpath = ''.join(path)
    dev = InputDevice(foundpath)

    power_wait_time = 1.5
    suspend = False

    # wait for the key release event so that we can differentiate
    # between long and short press
    state = {}

    while True:
        # Block for a 500ms or until there are events to be read.
        r, _, _ = select([dev], [], [], 0.5)

        if r:
            for event in dev.read():
                if event.type == ecodes.EV_KEY:
                    # When the key is pressed, record its timestamp.
                    if event.value == 1:
                        if event.code == ecodes.KEY_POWER and suspend:
                            print("ignoring power key on wakeup")
                            suspend = False
                        else:
                            state[event.code] = event.timestamp(), event
                            print("Key: %s %d %d pressed" % (ecodes.KEY[event.code], event.code, ecodes.KEY_POWER))

                    # When it's released check which key is is
                    if event.value == 0 and event.code in state:
                        delta = time() - event.timestamp()
                        print("Key: %s released %3.2f" % (ecodes.KEY[event.code], delta))
                        if event.code == ecodes.KEY_POWER and delta < power_wait_time:
                            # short power key press suspend the system
                            suspend = True
                            os.system("systemctl suspend -q")

                        del state[event.code]

        now = time()
        for code, ts_event in list(state.items()):
            ts, event = ts_event
            delta = now - ts
            if code == ecodes.KEY_POWER and delta >= power_wait_time and not suspend:
                # power key held for more than power_wait_time shut down the system
                os.system('shutdown -h now')


if __name__ == "__main__":
    sys.exit(main(sys.argv))
