from app import db
from app.models.post import Post
from app.models.attachment import Attachment
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, index=True)
    thread = db.relationship('Thread',
        backref=backref('comments', lazy='dynamic'),
        foreign_keys=thread_id)

    attachments = db.relationship('Attachment', back_populates='comment',
        lazy='joined')

    @property
    def is_top_comment(self):
        return self.id == self.thread.top_comment_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 delete(self):
        """Recursively delete post and all associated contents."""
        for a in self.attachments:
            a.delete()
        db.session.commit()
        db.session.delete(self)

    def create_attachments(self, multiple_file_field_data):
        """Create attachements from a form's MultipleFileField.data."""
        attachments = []
        for file in multiple_file_field_data:
            if file.filename != "":
                a = Attachment(file, self)
                attachments.append((a, file))
                db.session.add(a)
        db.session.commit()
        for a, file in attachments:
            a.set_file(file)

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