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:
    #   <sub_forums>  Children forums
    #   <topics>      List of topics in this exact forum (of type Topic)

    # Some configuration
    TOPICS_PER_PAGE = 30

    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 is_news(self):
        """Whether this forum is a news board."""
        return (self.parent is not None) and (self.parent.prefix == "news")

    def is_default_accessible(self):
        """Whether this forum can be read without privileges."""
        return (self.prefix != "admin") and (self.prefix != "creativecalc")

    def is_default_postable(self):
        """Whether this forum can be posted to without privileges."""
        return self.is_default_accessible() and (not self.is_news()) and \
               (self.sub_forums == [])

    def post_count(self):
        """Number of posts in every topic of the forum, without subforums."""
        # TODO: optimize this with real ORM
        return sum(t.thread.comments.count() for t in self.topics)

    def delete(self):
        """Recursively delete forum and all associated contents."""
        for t in self.topics:
            t.delete()
        db.session.commit()
        db.session.delete(self)

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