import os
import utils
from flask_sqlalchemy import SQLAlchemy
import flask
import random
from datetime import datetime
from user import User, db

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey("user.id"))
    title = db.Column(db.String(64))
    image_filename = db.Column(db.String(128))
    text = db.Column(db.String(512))
    publication_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    comments = db.relationship("Comment", backref="parent")
    
    @classmethod
    def register(cls, user, title, text, image_filename, commit=True):
        text = utils.clean_html(text)
        try:
            c = Post(user=user, title=title, text=text, image_filename=image_filename)
            db.session.add(c)
            # db.session.flush() #so that c is attributed an id ==> xxx still needed?
            # db.session.refresh(c)
            print("     adding post from", user.username, "img:", image_filename)
            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 "<Post: {} : --> img:{}>".format(self.id, self.image_filename)

    # def get_children_posts(self):
    #     print("GCP post")
    #     return [Post.query.get(id) for id in self.children_posts.split(",")[:-1]]

    def get_img_filename(self):
        if self.image_filename:
            url = flask.url_for('static', filename = os.path.join("images/",self.image_filename))
            return url
        return None


    def get_html(self, show_date=False, show_comments=False):
        html = ""
        html += '<div class="PostDiv">'
        if show_date:
            html += '<div class="CommentDate">' + self.user.username + ' : ' + \
                    self.publication_date.strftime('%d-%m-%Y %H:%M:%S') + '</div>'
        img_fn = self.get_img_filename()
        if img_fn:
            html += '<img class="GalleryImg" src="' + img_fn + \
                    '" alt="Image not found">'
        if show_comments:
            for c in self.comments:
                html += c.get_html()
        html += '</div>' #PostDiv
        return html



