from datetime import datetime
from app import db
from app.models.users import *


class Post(db.Model):
    __tablename__ = 'post'
    id = db.Column(db.Integer, primary_key=True)
    type = db.Column(db.String(20))
    __mapper_args__ = {
        'polymorphic_identity': __tablename__,
        'polymorphic_on': type
    }
    # Standalone properties
    text = db.Column(db.Text(convert_unicode=True))
    date_created = db.Column(db.DateTime, default=datetime.now)
    date_modified = db.Column(db.DateTime, default=datetime.now)
    # Relationships
    author_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

    def __init__(self, author, text):
        """ Create a Post """
        self.text = text
        if type(author) == Member:
            author = author.id
        self.author_id = author

    def update(self, text):
        """ Update a post. Check whether the request sender has the right to do
        this! """
        self.text = text
        self.date_modified = datetime.now()

    def change_ownership(self, new_author):
        """ Change ownership of a post. Check whether the request sender has the
        right to do this! """
        if type(new_author) == Member:
            new_author = new_author.id
        self.author_id = new_author

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