import base64
from pyzkfp import ZKFP2
import sys
import json


def fp_capture():
    zkfp2 = ZKFP2()
    zkfp2.Init()  # Initialize the ZKFP2 class

    allUserJson = sys.argv[1]  # Expecting a JSON string
    allUser = json.loads(allUserJson)  # Load the JSON into a Python list
    # print(allUser)
    # return

    # Get device count and open the first device
    device_count = zkfp2.GetDeviceCount()

    if device_count > 0:
        zkfp2.OpenDevice(0)  # Connect to the first device
        zkfp2.Light('white')

        while True:
            capture = zkfp2.AcquireFingerprint()
            if capture:
                tmp, img = capture  # `tmp` is the fingerprint template, `img` is the raw image data

                match_found = False  # Keep track if a match is found

                for user in allUser:
                    # Decode the Base64-encoded template1 into bytes
                    template1_bytes = bytearray(base64.b64decode(user['fingerprint']))
                    # Match the templates
                    res = zkfp2.DBMatch(template1_bytes, tmp) 

                    if res > 0:
                        zkfp2.Light('green')  # Light green if match found
                        # print(f"Fingerprint matched for user: {user['id']}")
                        print(user['id'])
                        match_found = True
                        break  # Exit the loop as match is found
                    else:
                        zkfp2.Light('red')  # Light red if not matched
                        # break

                if match_found:
                    break  # Exit the loop once a match is found
                else:
                    print("0")
                    break

if __name__ == "__main__":
    fp_capture()
