#!/usr/bin/python3

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

gpiokeys = {
    ecodes.KEY_WIMAX: 0,
    ecodes.KEY_WLAN: 0,
    ecodes.KEY_CAMERA: 0,
    ecodes.KEY_VOLUMEUP: 0,
    ecodes.KEY_VOLUMEDOWN: 0,
}

powerkey = {
    ecodes.KEY_POWER: 0
}

key_on = 1
key_off = 2


def keytest(name, keys):
    path = [path for path in evdev.list_devices() if evdev.InputDevice(path).name == name]
    if not path:
        print("key path not found ", path)
        return 1

    foundpath = ''.join(path)
    dev = InputDevice(foundpath)

    starttime = time()
    while time() - starttime < 60:
        # 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:
                    print("got key :", event)
                    if event.code in keys:
                        if event.value == 1:
                            keys[event.code] = keys[event.code] | key_on
                        elif event.value == 0:
                            keys[event.code] = keys[event.code] | key_off

        count = 0
        for key in keys:
            if keys[key] == 3:
                count = count + 1

        if count == len(keys):
            print("All keys toggled")
            return 0

    print("key test timed out ", keys)
    return 1


def testgpiokeys():
    print("toggle all of the switches and push the volume buttons")
    return keytest('gpio-keys', gpiokeys)


def testpowerkey():
    print("press and release the power button")
    return keytest('30370000.snvs:snvs-powerkey', powerkey)


def main(args):
    if testgpiokeys():
        print("gpio key test : FAILED")
        return 1

    if testpowerkey():
        print("power key test : FAILED")
        return 1

    print("key tests : PASSED")
    return 0


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