from datetime import datetime, timedelta
from sqlalchemy.dialects.postgresql import UUID
import uuid

import Models
from app import db


class DeviceModel(Models.Base):
    __tablename__ = 'devices'

    id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    user_id = db.Column(db.ForeignKey('user.id'), nullable=False)
    user = db.relationship(
        "UserModel",
        back_populates="devices"
    )
    device_id = db.Column(db.String, nullable=False, unique=True)
    device_name = db.Column(db.String, nullable=False, default="Unknown Device")
    last_active = db.Column(db.DateTime, nullable=False, default=datetime.utcnow())

    def is_stale(self):
        return timedelta(days=60) < datetime.utcnow() - self.last_active

    def delete(self):
        db.session.delete(self)
        db.session.commit()

    def __init__(self, **kwargs):
        self.last_active = datetime.utcnow()
        super().__init__(**kwargs)
