import cv2
import threading
import time
import face_processing as fp
from access_control_mqtt import access_control
from database import Database, Student, Parent
from display import Display

SERIAL_PORT_DISPLAY = "COM15"
CAMERA_INDEX = 0

cam = cv2.VideoCapture(CAMERA_INDEX)
actrl = access_control()
display = Display(SERIAL_PORT_DISPLAY)
db = Database()

global img
global frame_ready
frame_ready = False

def read_webcam():
    global img
    global frame_ready
    while True:
        ret, img = cam.read()
        frame_ready = True

threading.Thread(target=read_webcam).start()

while True:
    while not frame_ready:
        time.sleep(1)

    #Try to identify face
    if actrl.get_scan_state():
        print("SCAN ACTIVE!")
        faces = fp.identify_face(img, target_condidence=0.6)
        if(len(faces)==1):
            facefile = faces[0]
            parent_info = db.get_parent_info_file(facefile)
            if(parent_info!=None):
                pass
                #Open Door for parent
            else:
                student_info = db.get_student_info(facefile)
                if(student_info!=None):
                    #is student, request another scan for parent
                    parent_face = fp.identify_face(img, target_condidence=0.6)
                    if(len(faces)==1):
                        parent_info = db.get_parent_info(faces[0])
                        if(parent_info!=None):
                            if(db.check_relationship(student_info,parent_info)):
                                #Student is under parent, open door.
                                pass
                            else:
                                #Wrong Parent, retry.
                                pass
                        else:
                            #Not a parent, retry
                            pass
                    
        elif (len(faces)>1):
            #More than one people, error.
            pass
        else:
            #No one detected
            pass
        print("DONE")
