import utils
from flask_sqlalchemy import SQLAlchemy
import flask
import random
from datetime import datetime
from user import User, db


class Comment(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey("user.id"))
    parent_id = db.Column(db.Integer, db.ForeignKey("post.id"))
    text = db.Column(db.String(512))
    publication_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    comments = db.relationship("AnswerToComment", backref="parent")

    @classmethod
    def register(cls, user, text, parent, commit=True):
        text = utils.clean_html(text)
        try:
            c = Comment(user=user, text=text, parent=parent)
            db.session.add(c)
            # db.session.flush() #so that c is attributed an id
            # db.session.refresh(c)
            print("     adding comment from", user.username, "to post", parent.id)
            if commit:
                db.session.commit()
            return True
        except Exception as e:
            print("Failed to register " + cls.__name__)
            print("Error:", e)
            db.session.rollback()
            return False

    def __repr__(self):
        return "<Comment: {} : --> u:{}>".format(self.id, self.user.username)

    def get_html(self):
        html = ""
        html += '<div class="CommentDiv">'
        html += '<div class="CommentDate">' + self.user.username + ' : ' + \
                self.publication_date.strftime('%d-%m-%Y %H:%M:%S') + '</div>'
        html += '<div class="CommentText">' + self.text + '</div>'
        for c in self.comments:
            html += c.get_html()
        html += '</div>' #CommentDiv
        return html