from flask_hashids import HashidMixin
from app import db
from .corpus_follower_role import CorpusFollowerRole


class CorpusFollowerAssociation(HashidMixin, db.Model):
    __tablename__ = 'corpus_follower_associations'
    # Primary key
    id = db.Column(db.Integer, primary_key=True)
    # Foreign keys
    corpus_id = db.Column(db.Integer, db.ForeignKey('corpora.id'))
    follower_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    role_id = db.Column(db.Integer, db.ForeignKey('corpus_follower_roles.id'))
    # Relationships
    corpus = db.relationship(
        'Corpus',
        back_populates='corpus_follower_associations'
    )
    follower = db.relationship(
        'User',
        back_populates='corpus_follower_associations'
    )
    role = db.relationship(
        'CorpusFollowerRole',
        back_populates='corpus_follower_associations'
    )

    def __init__(self, **kwargs):
        if 'role' not in kwargs:
            kwargs['role'] = CorpusFollowerRole.query.filter_by(default=True).first()
        super().__init__(**kwargs)

    def __repr__(self):
        return f'<CorpusFollowerAssociation {self.follower.__repr__()} ~ {self.role.__repr__()} ~ {self.corpus.__repr__()}>'

    def to_json_serializeable(self, backrefs=False, relationships=False):
        json_serializeable = {
            'id': self.hashid,
            'corpus': self.corpus.to_json_serializeable(backrefs=True),
            'follower': self.follower.to_json_serializeable(),
            'role': self.role.to_json_serializeable()
        }
        if backrefs:
            pass
        if relationships:
            pass
        return json_serializeable