# ============================================================
# ADDITIVE: direct eSSL / ZK device connection (pull punches straight from the terminal over TCP, port 4370)
# One row per BiometricDevice that should be pulled directly. Nothing existing is altered:
# BiometricDevice, BiometricPunch and EsslSource are untouched. Imported by one extra line at the bottom of
# People/models.py.
# ============================================================
from django.db import models

from Company.models import company_details

from .att_models import BiometricDevice
from .models import Audit

__all__ = ["BiometricDeviceLink"]


class BiometricDeviceLink(Audit):
    DIRECTION_MODES = [("auto", "Auto (first scan IN, next OUT)"), ("device", "Use IN/OUT flag sent by the device")]
    STATUS = [("Idle", "Idle"), ("Running", "Running"), ("Success", "Success"), ("Error", "Error")]

    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="people_device_links")
    device = models.OneToOneField(BiometricDevice, on_delete=models.CASCADE, related_name="link")
    zk_port = models.PositiveIntegerField(default=4370)
    comm_key_enc = models.TextField(blank=True, null=True)            # Fernet token of the device Comm Key / password (never returned)
    pull_enabled = models.BooleanField(default=True)
    direction_mode = models.CharField(max_length=8, choices=DIRECTION_MODES, default="auto")
    min_gap_minutes = models.PositiveSmallIntegerField(default=2)     # a second scan inside this gap = double scan
    auto_enroll = models.BooleanField(default=False)                  # device UserID == employee_code -> enroll automatically
    pull_since = models.DateField(null=True, blank=True)              # ignore punches older than this
    cursor_time = models.DateTimeField(null=True, blank=True)         # newest punch time already pulled
    serial_number = models.CharField(max_length=60, blank=True, null=True)
    device_name = models.CharField(max_length=80, blank=True, null=True)
    last_status = models.CharField(max_length=8, choices=STATUS, default="Idle")
    running_since = models.DateTimeField(null=True, blank=True)
    last_pull_at = models.DateTimeField(null=True, blank=True)
    last_error = models.TextField(blank=True, null=True)
    total_pulled = models.PositiveBigIntegerField(default=0)

    class Meta:
        ordering = ["device__device_code"]
