"""This module defines the SQL data model for devices."""

import enum

from sqlalchemy import Column, ForeignKey, Integer, String, DateTime, Uuid
from sqlalchemy.sql.functions import now
from sqlalchemy.orm import relationship

from backend.database.engine import Base
from backend.models import records


class DeviceModel(Base):
    """Model for the device_model table."""

    __tablename__ = "device_models"

    id = Column('id', Integer, primary_key=True, autoincrement=True, index=True)
    name = Column('name', String, unique=True, nullable=False)
    picture_code = Column('picture_code', String, unique=True, nullable=False)

    instances = relationship("Device", back_populates="model", uselist=True, cascade="all, delete")


class Device(Base):
    """Model for the devices table."""

    __tablename__ = "devices"

    id = Column('id', Integer, primary_key=True, autoincrement=True, index=True)
    added = Column('added', DateTime(timezone=True), nullable=False, server_default=now())
    last_seen = Column('last_seen', DateTime(timezone=True), nullable=True, server_default=None)
    model_id = Column('model_id', Integer, ForeignKey('device_models.id', ondelete="CASCADE"), nullable=False)
    owner_id = Column('owner_id', Integer, ForeignKey('patients.user_id', ondelete="CASCADE"), nullable=False)

    model = relationship(DeviceModel, back_populates="instances", uselist=False)
    owner = relationship("Patient", back_populates="devices", uselist=False)

    heart_rate_records = relationship(records.HeartRateRecord, back_populates="device", uselist=True, cascade="all, delete")
    avpu_score_records = relationship(records.AvpuScoreRecord, back_populates="device", uselist=True, cascade="all, delete")
    blood_pressure_records = relationship(records.BloodPressureRecord, back_populates="device", uselist=True, cascade="all, delete")
    blood_oxygen_records = relationship(records.BloodOxygenRecord, back_populates="device", uselist=True, cascade="all, delete")
    body_temperature_records = relationship(records.BodyTemperatureRecord, back_populates="device", uselist=True, cascade="all, delete")
    respiration_score_records = relationship(records.RespirationScoreRecord, back_populates="device", uselist=True, cascade="all, delete")
