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

class Topic(Post):
    __tablename__ = 'topic'
    # ID of the underlying [Post] object
    id = db.Column(db.Integer, db.ForeignKey('post.id'), primary_key=True)

    __mapper_args__ = {
      'polymorphic_identity': __tablename__,
      # Because there is an extra relation to Post (promotion), SQLAlchemy
      # cannot guess which Post we inherit from; specify here.
      'inherit_condition': id == Post.id
    }

    # Post that the topic was promoted into. If this is not None, then the
    # topic was published into a project and a redirection should be emitted
    promotion_id = db.Column(db.Integer,db.ForeignKey('post.id'),nullable=True)
    promotion = db.relationship('Post', foreign_keys=promotion_id)

    # Topic title
    title = db.Column(db.Unicode(128))

    # Parent forum
    forum_id = db.Column(db.Integer, db.ForeignKey('forum.id'), nullable=False,
        index=True)
    forum = db.relationship('Forum',
        backref=backref('topics', lazy='dynamic'), foreign_keys=forum_id)

    # Associated thread
    thread_id = db.Column(db.Integer,db.ForeignKey('thread.id'),nullable=False)
    thread = db.relationship('Thread', foreign_keys=thread_id,
                back_populates='owner_topic')

    # Number of views in the forum
    views = db.Column(db.Integer)

    def __init__(self, forum, author, title, thread):
        """
        Create a Topic.

        Arguments:
        forum  -- parent forum or sub-forum (Forum)
        author -- post author (User)
        title  -- topic title (unicode string)
        thread -- discussion thread attached to the topic (Thread)
        """

        Post.__init__(self, author)
        self.title = title
        self.views = 0
        self.thread = thread
        self.forum = forum

    def delete(self):
        """Recursively delete topic and all associated contents."""
        if self.promotion is None:
            self.thread.delete()
        db.session.delete(self)

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