from app import db

# Trophy: Achievements granted to users for performing specific actions
class Trophy(db.Model):
    __tablename__ = 'trophy'

    # Trophy ID and type (polymorphic discriminator)
    id = db.Column(db.Integer, primary_key=True)
    type = db.Column(db.String(20))

    __mapper_args__ = {
        'polymorphic_identity': __tablename__,
        'polymorphic_on': type
    }

    # Trophy name (in French)
    name = db.Column(db.Unicode(64), index=True)
    # Description
    description = db.Column(db.UnicodeText, index=True)
    # Hidden by default
    hidden = db.Column(db.Boolean, default=False)

    owners = db.relationship('Member', secondary=lambda: TrophyMember,
        back_populates='trophies')

    def __init__(self, name, description, hidden=False):
        self.name = name
        self.description = description
        self.hidden = hidden

    def delete(self):
        for owner in self.owners:
            owner.del_trophy(self)
            db.session.add(owner)
        db.session.commit()
        db.session.delete(self)

    def __repr__(self):
        return f'<Trophy: {self.name}>'

# Title: Rare trophies that can be displayed along one's name
class Title(Trophy):
    __tablename__ = 'title'
    __mapper_args__ = {'polymorphic_identity': __tablename__}

    id = db.Column(db.Integer, db.ForeignKey('trophy.id'), primary_key=True)
    css = db.Column(db.UnicodeText)

    def __init__(self, name, description, hidden=False, css=""):
        self.name = name
        self.description = description
        self.hidden = hidden
        self.css = css

    def __repr__(self):
        return f'<Title: {self.name}>'


# Many-to-many relation for users earning trophies
TrophyMember = db.Table('trophy_member', db.Model.metadata,
    db.Column('tid', db.Integer, db.ForeignKey('trophy.id')),
    db.Column('uid', db.Integer, db.ForeignKey('member.id'), index=True))
