from datetime import datetime
from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Integer, String
from db import Base, CRUD
import utils


class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    login = Column(String, unique=True, index=True)
    username = Column(String, unique=True, index=True)
    photo = Column(String, default="static/images/users/default.png")
    hashed_password = Column(String)
    access_level_id = Column(Integer, ForeignKey("access_level.id", ondelete="CASCADE"))
    is_active = Column(Boolean, default=True)
    created_at = Column(DateTime, default=datetime.now)
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)

    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)

    def toDict(self):
        return utils.toDict(self)

    async def save(self) -> "User":
        return await CRUD.create(self, refresh=True)

    async def edit(self, **kwargs) -> "User":
        return await CRUD.update(User, self.id, **kwargs)
