import xgboost as xb
import face_recognition
import os
from os import listdir
from os.path import isfile, join
import sys
import time
import cv2
import numpy
import array
import glob
import errno
import pickle



def getReferences(dir):
    subdirs=listdir(dir) 
    names=[];
    emb=[]
    for subdir in (subdirs):
        name=subdir
        subdir=join(dir,subdir)
        txtFile = open(subdir + '/' + name + '.txt', 'r')
        text=txtFile.read()
        text=text.replace("]", "")
        text=text.replace("[", "")
        result=text.split()
        f=[]
        for n in range(0,128):
            f.append(float(result[n]))
        features=numpy.array(f)
        emb.append(features)
        names.append(name)
        txtFile.close()
    return emb, names

def main(dir,distance):
    subdirs=listdir(dir)  
    gbm=[]
    for subdir in (subdirs):
        name=subdir
        gbm.append(pickle.load(open("xgboost_results_"+name+".txt", "rb")))
    TP=0
    FP=0
    FN=0
    TN=0
    total=0   
    subdirs=listdir(dir)  
    resultFeatures = []
    for n,subdir in enumerate(subdirs):
        name=subdir
        subdir=join(dir,subdir)
        files=[f for f in listdir(subdir) if isfile(join(subdir,f))]
        for file in (files):
            file=join(subdir,file);
            videoCapture=cv2.VideoCapture(file)
            if (not videoCapture.isOpened()):
                continue
            embeddings=[]
            ret,frame=videoCapture.read()
            while(ret):
                image=cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)
                encodings=face_recognition.face_encodings(image)
                if (encodings):
                    embeddings.append(encodings[0])    
                ret,frame=videoCapture.read()
            for idx,model in enumerate(gbm):
                predictions = model.predict_proba(embeddings)
                for p in predictions:
                    if (p[1]>distance):
                        if (idx==n):
                            TP=TP+1
                        else:
                            FP=FP+1
                    else:
                        if (idx==n): 
                            FN=FN+1
                        else:
                            TN=TN+1
                    total=total+1
        print("TP=",TP," FP=",FP," FN=",FN," TN=",TN," Total=",total)



if __name__=="__main__":
	if len(sys.argv)> 1:
		path = sys.argv[1]
	else:
		path = "./database2"
	sys.exit(int(main(path,0.04)) or 0)