import torch


def getKNeighbors(X, y, image_to_test, k):
    """
    
    This function calculate the distance between an encoding face test_image and the encoding face database. 
    Then it select the k closest encoding face. 
    
    :param X: list of all the encoding face database (output of facetensordatabase() function)
    :param y: list of the name corresponding to these encoding face (output of facetensordatabase() function)
    :param image_to_test: encoding face to test against the database
    :param k: numbers of closest neighbours we want to use for the KNN
    
    :return: returns 1 variables: A list containing tuple organised as follow: (face_encoding tensor, distance, name)
    
    """
    X=torch.stack(X)
    #print(image_to_test.shape)
    dist=((image_to_test - X)**2)
    dist=dist.sum(axis=1)
    dist=torch.sqrt(dist)
    
    value, indices = torch.sort(dist)
    close_neighbors=[]
    for x in range (k):
        close_neighbors.append((X[indices[x]], value[x], y[indices[x]]))
    return close_neighbors