import re

import evdev
from evdev import InputDevice, categorize, ecodes
from six import unichr

key_map = {
            evdev.ecodes.KEY_A: 'a', evdev.ecodes.KEY_B: 'b', evdev.ecodes.KEY_C: 'c', evdev.ecodes.KEY_D: 'd', evdev.ecodes.KEY_E: 'e',
            evdev.ecodes.KEY_F: 'f', evdev.ecodes.KEY_G: 'g', evdev.ecodes.KEY_H: 'h', evdev.ecodes.KEY_I: 'i', evdev.ecodes.KEY_J: 'j',
            evdev.ecodes.KEY_K: 'k', evdev.ecodes.KEY_L: 'l', evdev.ecodes.KEY_M: 'm', evdev.ecodes.KEY_N: 'n', evdev.ecodes.KEY_O: 'o',
            evdev.ecodes.KEY_P: 'p', evdev.ecodes.KEY_Q: 'q', evdev.ecodes.KEY_R: 'r', evdev.ecodes.KEY_S: 's', evdev.ecodes.KEY_T: 't',
            evdev.ecodes.KEY_U: 'u', evdev.ecodes.KEY_V: 'v', evdev.ecodes.KEY_W: 'w', evdev.ecodes.KEY_X: 'x', evdev.ecodes.KEY_Y: 'y',
            evdev.ecodes.KEY_Z: 'z',
            evdev.ecodes.KEY_1: '1', evdev.ecodes.KEY_2: '2', evdev.ecodes.KEY_3: '3', evdev.ecodes.KEY_4: '4', evdev.ecodes.KEY_5: '5',
            evdev.ecodes.KEY_6: '6', evdev.ecodes.KEY_7: '7', evdev.ecodes.KEY_8: '8', evdev.ecodes.KEY_9: '9', evdev.ecodes.KEY_0: '0',
            evdev.ecodes.KEY_SPACE: ' ',
            evdev.ecodes.KEY_DOT: '.',
            evdev.ecodes.KEY_ENTER: '\n', # Or handle enter as needed
            evdev.ecodes.KEY_BACKSPACE: '\b',
            evdev.ecodes.KEY_LEFTSHIFT: '',
            evdev.ecodes.KEY_SLASH: '/',

        }

def capture_input_events():
    try:
        # List available input devices
        devices = [InputDevice(path) for path in evdev.list_devices()]

        device_path = find_barcode_scanner_event(devices)
        device = InputDevice(device_path)

        print(f"Capturing events from {device.name}...")

        for event in device.read_loop():
            if event.type == ecodes.EV_KEY:
                if event.code in key_map and event.value == 1:
                    print(key_map[event.code],end='')
                else:
                    if event.value == 0:
                        continue
                    print(categorize(event))
                    #print("UNKNOWN CODE ",event.code)
            elif event.type == ecodes.EV_REL:
                pass #print(categorize(event))
            elif event.type == ecodes.EV_ABS:
               print(categorize(event))
            else:
                pass # print(event)

    except FileNotFoundError:
        print("Device not found.")
    except KeyboardInterrupt:
        print("Capture stopped.")


def find_barcode_scanner_event(input_list):
    """
    Finds the input identifier for the "Symbol Bar Code Scanner" in a list of input device strings.

    Args:
        input_list: A list of strings, each representing an input device.

    Returns:
        The input identifier (e.g., "/dev/input/event3") if found, otherwise None.
    """
    for line in input_list:
        if "Symbol Bar Code Scanner" in line.name:
            return line.path
    return None


if __name__ == "__main__":
    capture_input_events()