from app import db
from app.models.post import Post
from sqlalchemy.orm import backref

class Comment(Post):
    __tablename__ = 'comment'
    __mapper_args__ = {'polymorphic_identity': __tablename__}

    # ID of the underlying Post object
    id = db.Column(db.Integer, db.ForeignKey('post.id'), primary_key=True)

    # Comment contents
    text = db.Column(db.UnicodeText)

    # Parent thread
    thread_id = db.Column(db.Integer, db.ForeignKey('thread.id'),
        nullable=False)
    thread = db.relationship('Thread',
        backref=backref('comments', lazy='dynamic'),
        foreign_keys=thread_id)

    def __init__(self, author, text, thread):
        """
        Create a new Comment in a thread.

        Arguments:
        author -- comment poster (User)
        text   -- contents (unicode string)
        thread -- parent discussion thread (Thread)
        """

        Post.__init__(self, author)
        self.thread = thread
        self.text = text

    def edit(self, new_text):
        """Edit a Comment's contents."""

        self.text = new_text
        self.touch()

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