# Path: securedpi_locks/models.py
# class Lock(models.Model):
#     """Define class for user profile."""
#     user = models.ForeignKey(
#         settings.AUTH_USER_MODEL,
#         related_name='locks',
#         on_delete=models.CASCADE
#     )
#     name = models.CharField(max_length=20)
#     location = models.CharField(max_length=50)
#     description = models.CharField(max_length=50, blank=True)
#     date_created = models.DateField(auto_now_add=True)
#     date_modified = models.DateField(auto_now=True)
#     serial = models.CharField(max_length=50, unique=True)
#     status = models.CharField(max_length=20, default='unlocked')
#     is_active = models.BooleanField(default=False)
#     facial_recognition = models.BooleanField(default=False)
#     RFID = models.CharField(max_length=100, blank=True)
# 
#     def __str__(self):
#         return 'Lock for {}'.format(self.user)
# 
# Path: securedpi_facerec/facial_recognition/facial_recognition.py
# HERE = os.path.dirname(os.path.abspath(__file__))
# CASCADE_MODEL = os.path.join(HERE, 'haarcascade_frontalface_default.xml')
# FACE_CASCADE = cv2.CascadeClassifier(CASCADE_MODEL)
# TRAINING_SET_PATH = os.path.join(MEDIA_ROOT, 'training')
# RECOG_MODEL = os.path.join(HERE, 'recog_brain.yml')
# def train_recognizer(recognizer=cv2.face.createLBPHFaceRecognizer,
#                      image_path=TRAINING_SET_PATH,
#                      save_file=os.path.join(HERE, 'recog_brain.yml'),
#                      recog_model=None,
#                      demo=False):
# def test_individual(image_to_test, recog_model=RECOG_MODEL, verbose=False):
# 
# Path: securedpi/settings.py
# FLASK_SERVER = os.environ.get('FLASK_SERVER')
# 
# UNCERTAINTY_THRESHOLD = 45


from django.db import models
from django.contrib.auth.models import User
from django.utils.encoding import python_2_unicode_compatible
from securedpi_locks.models import Lock
from django.db.models.signals import post_save
from django.dispatch import receiver
from securedpi_facerec.facial_recognition import facial_recognition
from securedpi.settings import FLASK_SERVER, UNCERTAINTY_THRESHOLD
import requests
        return 'Event for {}'.format(self.lock_id)


@receiver(post_save, sender=Event)
def start_FR(sender, **kwargs):
    """
    Initiate facial recognition method with received photo.

    If the photo and RFID are recognized, make post request to rasp pi to
    unlock.
    """
    event = kwargs['instance']
    lock = Lock.objects.get(pk=event.lock_id)
    user_owns_lock = False
    confidence_acceptable = None

    if event.photo and lock.status == 'locked':
        dj_decision = facial_recognition.test_individual(
            event.photo.url,
            verbose=True)
        try:
            username = User.objects.get(pk=dj_decision[0]).username
            user_owns_lock = dj_decision[0] == lock.user.pk
            print('User has access to lock: ', user_owns_lock)
        except:
            print('No facial recognition made. Check if yml file exists!')
            dj_decision = ('', None)
        if dj_decision[0]:
            print('**face recognized: ', dj_decision[0], ' as member ', username)
            confidence_acceptable = dj_decision[1] < UNCERTAINTY_THRESHOLD

# Path: securedpi_locks/models.py
# class Lock(models.Model):
#     """Define class for user profile."""
#     user = models.ForeignKey(
#         settings.AUTH_USER_MODEL,
#         related_name='locks',
#         on_delete=models.CASCADE
#     )
#     name = models.CharField(max_length=20)
#     location = models.CharField(max_length=50)
#     description = models.CharField(max_length=50, blank=True)
#     date_created = models.DateField(auto_now_add=True)
#     date_modified = models.DateField(auto_now=True)
#     serial = models.CharField(max_length=50, unique=True)
#     status = models.CharField(max_length=20, default='unlocked')
#     is_active = models.BooleanField(default=False)
#     facial_recognition = models.BooleanField(default=False)
#     RFID = models.CharField(max_length=100, blank=True)
# 
#     def __str__(self):
#         return 'Lock for {}'.format(self.user)
# 
# Path: securedpi_facerec/facial_recognition/facial_recognition.py
# HERE = os.path.dirname(os.path.abspath(__file__))
# CASCADE_MODEL = os.path.join(HERE, 'haarcascade_frontalface_default.xml')
# FACE_CASCADE = cv2.CascadeClassifier(CASCADE_MODEL)
# TRAINING_SET_PATH = os.path.join(MEDIA_ROOT, 'training')
# RECOG_MODEL = os.path.join(HERE, 'recog_brain.yml')
# def train_recognizer(recognizer=cv2.face.createLBPHFaceRecognizer,
#                      image_path=TRAINING_SET_PATH,
#                      save_file=os.path.join(HERE, 'recog_brain.yml'),
#                      recog_model=None,
#                      demo=False):
# def test_individual(image_to_test, recog_model=RECOG_MODEL, verbose=False):
# 
# Path: securedpi/settings.py
# FLASK_SERVER = os.environ.get('FLASK_SERVER')
# 
# UNCERTAINTY_THRESHOLD = 45


# Path: securedpi_events/models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils.encoding import python_2_unicode_compatible
from securedpi_locks.models import Lock
from django.db.models.signals import post_save
from django.dispatch import receiver
from securedpi_facerec.facial_recognition import facial_recognition
from securedpi.settings import FLASK_SERVER, UNCERTAINTY_THRESHOLD
import requests

        return 'Event for {}'.format(self.lock_id)


@receiver(post_save, sender=Event)
def start_FR(sender, **kwargs):
    """
    Initiate facial recognition method with received photo.

    If the photo and RFID are recognized, make post request to rasp pi to
    unlock.
    """
    event = kwargs['instance']
    lock = Lock.objects.get(pk=event.lock_id)
    user_owns_lock = False
    confidence_acceptable = None

    if event.photo and lock.status == 'locked':
        dj_decision = facial_recognition.test_individual(
            event.photo.url,
            verbose=True)
        try:
            username = User.objects.get(pk=dj_decision[0]).username
            user_owns_lock = dj_decision[0] == lock.user.pk
            print('User has access to lock: ', user_owns_lock)
        except:
            print('No facial recognition made. Check if yml file exists!')
            dj_decision = ('', None)
        if dj_decision[0]:
            print('**face recognized: ', dj_decision[0], ' as member ', username)
            confidence_acceptable = dj_decision[1] < UNCERTAINTY_THRESHOLD

        elif not lock.facial_recognition: