from app import db

class Thread(db.Model):
    """Some thread, such as a topic, program, tutorial."""

    __tablename__ = 'thread'

    # Unique ID
    id = db.Column(db.Integer, primary_key=True)

    # Top comment
    top_comment_id = db.Column(db.Integer, db.ForeignKey('comment.id'))
    top_comment    = db.relationship('Comment', foreign_keys=top_comment_id)

    # Other fields populated automatically through relations:
    #  <comments>   The list of comments (of type Comment)

    def __init__(self):
        """
        Create a empty Thread. Normally threads are not meant to be empty, so
        you should create a Comment with this thread as parent, then assign it
        as top comment with a call to set_top_comment().
        """
        self.top_comment_id = None

    def set_top_comment(self, top_comment):
        """
        Changes the top comment of the thread. The old top comment will usually
        become visible in the flow of posts instead of being pinned at the top.

        Arguments:
        top_comment -- new top comment, must belong to this thread
        """

        if top_comment not in self.comments:
            raise Exception("Cannot set foreign comment as top thread comment")

        self.top_comment = top_comment

    def __repr__(self):
        return f'<Thread: #{self.id}>'
