from datetime import datetime

import bcrypt as _bcrypt
from sqlalchemy import Boolean, Column, DateTime, Integer, String

from database import Base


class Benutzer(Base):
    __tablename__ = "benutzer"

    id = Column(Integer, primary_key=True, autoincrement=True)
    kuerzel = Column(String(10), unique=True, nullable=False)
    name = Column(String(100), nullable=False)
    email = Column(String(200))
    passwort_hash = Column(String(200))
    ist_aktiv = Column(Boolean, default=True)
    ist_admin = Column(Boolean, default=False)
    letzter_login = Column(DateTime)
    erfasst_am = Column(DateTime, default=datetime.now)

    def set_passwort(self, passwort: str):
        self.passwort_hash = _bcrypt.hashpw(
            passwort.encode("utf-8"), _bcrypt.gensalt()
        ).decode("utf-8")

    def check_passwort(self, passwort: str) -> bool:
        if not self.passwort_hash:
            return False
        return _bcrypt.checkpw(
            passwort.encode("utf-8"),
            self.passwort_hash.encode("utf-8"),
        )
