from app import db


class Forum(db.Model):
    __tablename__ = 'forum'
    id = db.Column(db.Integer, primary_key=True)

    # Forum name, as displayed on the site (eg. "Problèmes de transfert")
    name = db.Column(db.Unicode(64))
    # Privilege prefix (sort of slug) for single-forum privileges (lowercase)
    prefix = db.Column(db.Unicode(64))
    # Forum description, as displayed on the site
    descr = db.Column(db.UnicodeText)
    # Forum URL, for dynamic routes
    url = db.Column(db.String(64))

    # Relationships
    parent_id = db.Column(db.Integer, db.ForeignKey('forum.id'), nullable=True)
    parent    = db.relationship('Forum', backref='sub_forums', remote_side=id,
                    lazy=True, foreign_keys=parent_id)

    # Other fields populated automatically through relations:
    #   <topics>   List of topics in this exact forum (of type Topic)

    def __init__(self, url, name, prefix, descr="", parent=None):
        self.url = url
        self.name = name
        self.descr = descr
        self.prefix = prefix

        if isinstance(parent, str):
            self.parent = Forum.query.filter_by(url=str).first()
        else:
            self.parent = parent

    def post_count(self):
        """Number of posts in every topic of the forum, without subforums."""
        return sum(len(t.thread.comments) for t in self.topics)

    def __repr__(self):
        return f'<Forum: {self.name}>'
