from datetime import datetime

from sqlalchemy import Column, ForeignKey, Integer, String, Boolean
from sqlalchemy.orm import relationship, mapped_column, Mapped

from src.db.models.base import Base, BaseMixin


class Profile(Base, BaseMixin):
    __tablename__ = 'profile'
    first_name = Column(String)
    last_name = Column(String)
    user_name = Column(String, nullable=False)
    email = Column(String)
    password = Column(String)
    enabled = Column(Boolean)
    assignments = relationship("Assignment")
    tokens = relationship("Token")

    def get_full_name(self) -> str:
        full_name = ""
        if self.first_name is not None:
            full_name += self.first_name
        if self.last_name is not None:
            if len(full_name) > 0:
                full_name += " "
            full_name += self.last_name
        return full_name

    def __str__(self):
        return f"Profile({self.id} {self.user_name}, {self.email})"


class Token(Base, BaseMixin):
    __tablename__ = "token"
    token = Column(String, nullable=False, unique=True)
    name = Column(String)
    last_used_date: Mapped[datetime] = mapped_column()
    enabled = Column(Boolean)
    profile_id = Column(String, ForeignKey("profile.id"), nullable=False)
    profile = relationship("Profile", back_populates="tokens")


class Permission(Base, BaseMixin):
    __tablename__ = "permission"
    name = Column(String, nullable=False)
    assignments = relationship("Assignment")


class Assignment(Base, BaseMixin):
    __tablename__ = "assignment"
    profile_id = Column(String, ForeignKey("profile.id"), nullable=False)
    profile = relationship("Profile", back_populates="assignments")
    permission_id = Column(String, ForeignKey("permission.id"), nullable=False)
    permission = relationship("Permission", back_populates="assignments")


class MailAccount(Base, BaseMixin):
    __tablename__ = "mail_account"
    host = Column(String)
    port = Column(Integer)
    protocol = Column(String)
    user_name = Column(String)
    password = Column(String)
    start_tls = Column(Boolean)


class Mail(Base, BaseMixin):
    __tablename__ = "mail"
    folder: Mapped[str] = mapped_column()
    subject: Mapped[str] = mapped_column()
    body: Mapped[str] = mapped_column()
    sent_date: Mapped[datetime] = mapped_column()
    received_date: Mapped[datetime] = mapped_column()
