from app.extensions import db
from datetime import datetime, timedelta

LOCK_TIMEOUT = timedelta(minutes=2)

class Aufmass(db.Model):
    __tablename__ = 'aufmass'

    id = db.Column(db.Integer, primary_key=True)
    project_id = db.Column(db.Integer, db.ForeignKey('projekte.id'), nullable=False)
    name = db.Column(db.String(200), nullable=False, default='Standard')
    typ = db.Column(db.String(50), default='')
    status = db.Column(db.String(20), default='aktiv')
    sortierung = db.Column(db.Integer, default=0)
    bemerkung = db.Column(db.Text)
    erstellt_von = db.Column(db.Integer, db.ForeignKey('users.id'))
    erstellt_am = db.Column(db.DateTime, default=datetime.utcnow)
    geaendert_am = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    locked_by = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True)
    locked_at = db.Column(db.DateTime, nullable=True)

    positionen = db.relationship('Position', backref='aufmass_ref', lazy='dynamic',
                                  cascade='all, delete-orphan', order_by='Position.sortierung')

    def is_locked(self):
        if not self.locked_by or not self.locked_at:
            return False, None
        if datetime.utcnow() - self.locked_at > LOCK_TIMEOUT:
            return False, None
        return True, self.locked_by

    def try_lock(self, user_id):
        locked, holder = self.is_locked()
        if locked and holder != user_id:
            return False
        self.locked_by = user_id
        self.locked_at = datetime.utcnow()
        return True

    def unlock(self):
        self.locked_by = None
        self.locked_at = None

    def refresh_lock(self, user_id):
        if self.locked_by == user_id:
            self.locked_at = datetime.utcnow()
            return True
        return False

    def __repr__(self):
        return f'<Aufmass {self.name} @ {self.project_id}>'
