from typing import Optional
import sqlalchemy as sa
import sqlalchemy.orm as so
from app import db
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
from app import login

class User(UserMixin, db.Model):
    id: so.Mapped[int] = so.mapped_column(primary_key=True)
    username: so.Mapped[str] = so.mapped_column(sa.String(64), index=True,
                                                unique=True)
    password_hash: so.Mapped[Optional[str]] = so.mapped_column(sa.String(256))

    def set_password(self, password: str) -> None:
        self.password_hash = generate_password_hash(password)

    def check_password(self, password: str) -> bool:
        return check_password_hash(self.password_hash, password)

    def __repr__(self):
        return '<User {}>'.format(self.username)

class Setting(db.Model):
    id: so.Mapped[int] = so.mapped_column(primary_key=True)
    key: so.Mapped[str] = so.mapped_column(sa.String(255), index=True,
                                                unique=True, nullable=False)
    value: so.Mapped[str] = so.mapped_column(sa.String(255))

    def __repr__(self):
        return '<Setting {}>'.format(self.key)

@login.user_loader
def load_user(user_id: str) -> User:
    return db.session.get(User, int(user_id))