from sqlalchemy.orm import Session

from model import models
from model.Lecture import LectureBase
from repo.AbstractLectureRepository import AbstractLectureRepository


class LectureRepository(AbstractLectureRepository):

    def __init__(self, db: Session):
        self.db = db

    def create(self, lecture: LectureBase):
        new_lecture = models.Lecture()
        # id set to incremental, we do not need to specify it here
        new_lecture.text = lecture.text
        new_lecture.summary = lecture.summary
        new_lecture.lecturer = lecture.lecturer
        new_lecture.voice_language = lecture.voice_language
        new_lecture.slides_language = lecture.slides_language
        new_lecture.duration_seconds = lecture.duration_seconds

        for topic in lecture.topics:
            # check if the topic is new or not
            db_topic = self.db.query(models.Topic).filter(models.Topic.topic_category == topic.topic_category).first()
            if not db_topic:
                # we must create a new one
                new_topic = models.Topic()
                new_topic.topic_category = topic.topic_category
                self.db.add(new_topic)
                self.db.commit()
                self.db.refresh(new_topic)
                db_topic = new_topic

            new_lecture_topic = models.LectureTopic()
            new_lecture_topic.topic = db_topic
            new_lecture.lecture = new_lecture
            new_lecture_topic.topic_probability = topic.probability

            new_lecture.topics.append(new_lecture_topic)

        for img in lecture.images:
            db_image = models.Image()
            db_image.image_url = img.image_url

            new_lecture.images.append(db_image)

        for vdu_data_item in lecture.vdu_data:
            db_vdu_data = models.VisualDocUnderstandingData()
            db_vdu_data.vdu_output = vdu_data_item.vdu_output
            db_vdu_data.vdu_model = vdu_data_item.vdu_model

            new_lecture.visual_doc_understanding_data.append(db_vdu_data)

        self.db.add(new_lecture)
        self.db.commit()
        self.db.refresh(new_lecture) ## maybe it is not needed
        return new_lecture

    def get(self, lecture_id: int):
        return self.db.query(models.Lecture).filter(models.Lecture.id == lecture_id).first()

    def get_list(self, limit: int = 10, offset: int = 0):
        return self.db.query(models.Lecture).offset(offset).limit(limit).all()

    def delete(self, lecture_id: int):
        db_lecture = self.db.query(models.Lecture).filter(models.Lecture.id == lecture_id).first()
        if db_lecture:
            self.db.delete(db_lecture)
            self.db.commit()
            return True
        else:
            return False


