from sqlalchemy import text
from sqlalchemy.dialects.postgresql import UUID
import uuid

import Models
from app import db
from Models import MediaLikesModel


class MediaModel(Models.Base):
    __tablename__ = 'media'

    id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    title = db.Column(db.String, nullable=True)
    description = db.Column(db.String, nullable=True)
    link = db.Column(db.String, nullable=True)
    icon = db.Column(db.String, nullable=True)
    reviewed = db.Column(db.Boolean, nullable=False, default=True)
    order = db.Column(db.Integer, nullable=False)
    project_id = db.Column(db.ForeignKey('project.id'), nullable=False)
    project = db.relationship(
        "ProjectModel",
        foreign_keys=project_id,
        back_populates="media"
    )
    submitter_id = db.Column(db.ForeignKey('user.id'), nullable=False)
    submitter = db.relationship(
        "UserModel"
    )

    @property
    def likes(self):
        return MediaLikesModel.query.filter(MediaLikesModel.media == self).count()

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def is_liked_by(self, user):
        return MediaLikesModel.query.filter(
            MediaLikesModel.media == self,
            MediaLikesModel.user == user
        ).all() != []

    def get_liked_by(self, user):
        if user is not self.submitter and not self.is_liked_by(user):
            db.session.add(MediaLikesModel(media=self, user=user))
            db.session.commit()

    def get_unliked_by(self, user):
        db.session.delete(
            MediaLikesModel.query.filter(
                MediaLikesModel.media == self,
                MediaLikesModel.user == user
            ).first()
        )
        db.session.commit()

    def delete(self):
        db.engine.execute(text(f"DELETE FROM media_likes WHERE media_id = '{self.id}';"))
        db.session.delete(self)
        db.session.commit()
