from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.ext.hybrid import hybrid_property

import uuid
import Models
from app import db


class ChannelModel(Models.Base):
    __tablename__ = "channel"

    id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)

    @hybrid_property
    def last_post(self):
        return Models.PostModel.query.filter(Models.PostModel.channel == self).order_by(
            Models.PostModel.date_created.desc()).first()

    project = db.relationship(
        "ProjectModel",
        back_populates="channel",
        uselist=False
    )
    chat = db.relationship(
        "ChatModel",
        back_populates="channel",
        uselist=False
    )
    posts = db.relationship(
        "PostModel",
        primaryjoin="ChannelModel.id==PostModel.channel_id",
        cascade="all, delete-orphan"
    )

    def get_last_read_message(self, user):
        last_read = Models.LastReadMessageModel.query.get((user.id, self.id))
        if last_read and last_read.post:
            return last_read.post
        return None

    def has_new_messages(self, user):
        return self.last_post != self.get_last_read_message(user)

    def delete(self):
        for post in self.posts:
            post.delete()

    def post_before(self, post):
        return Models.PostModel.query\
            .filter(Models.PostModel.channel == self)\
            .filter(Models.PostModel.date_created < post.date_created)\
            .order_by(Models.PostModel.date_created.desc())\
            .first()


main_channel_id = 'fa050858-1d94-11ec-9621-0242ac130002'


def create_main_channel():
    main_channel = ChannelModel(id=uuid.UUID(main_channel_id))
    db.session.add(main_channel)
    db.session.commit()
    return main_channel


def get_main_channel():
    main_channel = ChannelModel.query.get(main_channel_id)
    if not main_channel:
        return create_main_channel()
    return main_channel
