from app import db
from app.models.post import Post

class Program(Post):
    __tablename__ = 'program'
    __mapper_args__ = {'polymorphic_identity': __tablename__}

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

    # Program name
    name = db.Column(db.Unicode(128))
    # Author, when different from the poster
    real_author = db.Column(db.Unicode(128))
    # Version
    version = db.Column(db.Unicode(64))
    # Approximate size as indicated by poster
    size = db.Column(db.Unicode(64))
    # License identifier
    license = db.Column(db.String(32))

    # Label de qualité
    label = db.Column(db.Boolean, nullable=False, server_default="FALSE")
    # Event for which the program was posted
    event = db.Column(db.Integer, db.ForeignKey('event.id'), nullable=True)

    # TODO: Number of downloads

    # Thread with the program description (top comment) and comments
    thread_id = db.Column(db.Integer,db.ForeignKey('thread.id'),nullable=False)
    thread = db.relationship('Thread', foreign_keys=thread_id,
        back_populates='owner_program')

    # Progrank, and last date of progrank update
    progrank = db.Column(db.Integer)
    progrank_date = db.Column(db.DateTime)

    # Implicit attributes:
    # * tags (inherited from Post)
    # * attachements (available at thread.top_comment.attachments)

    def __init__(self, author, name, thread):
        """
        Create a Program.

        Arguments:
        author -- post author (User, though only Members can post)
        name   -- program name (unicode string)
        thread -- discussion thread attached to the topic
        """

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

    @staticmethod
    def from_topic(topic):
        p = Program(topic.author, topic.title, topic.thread)
        topic.promotion = p

    def delete(self):
        db.session.delete(self)

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