package de.sebse.fuplanner2.database

import androidx.lifecycle.LiveData
import androidx.room.*

@Dao
interface CourseDao {
    @Query("SELECT * FROM course ORDER BY year DESC, CASE WHEN isSummerSemester THEN 1 ELSE 0 END ASC, title ASC")
    fun getAll(): LiveData<List<Course>>

    @Query("SELECT * FROM course INNER JOIN (SELECT year, CASE WHEN isSummerSemester THEN 1 ELSE 0 END AS semester FROM course GROUP BY year, isSummerSemester ORDER BY year DESC, semester ASC LIMIT 1) current WHERE current.year = course.year AND current.semester = CASE WHEN course.isSummerSemester THEN 1 ELSE 0 END ORDER BY title ASC")
    fun getLatestSemester(): LiveData<List<Course>>

    @Query("SELECT year, CASE WHEN isSummerSemester THEN 1 ELSE 0 END AS semester FROM course GROUP BY year, isSummerSemester ORDER BY year DESC, semester ASC LIMIT 1")
    fun getLatestSemesterName(): Semester

    @Query("SELECT * FROM course WHERE uid = :courseId")
    fun getCourseById(courseId: Long): LiveData<Course>

    @Query("SELECT * FROM course WHERE uid = :courseId")
    fun getCourseById2(courseId: Long): Course

    @Query("SELECT * FROM course WHERE userId = :userId AND (moduleType & :moduleType) == :moduleType")
    fun getAllByType(userId: Long, moduleType: Int): List<Course>

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insert(course: Course): Long

    @Update(onConflict = OnConflictStrategy.REPLACE)
    fun update(course: Course)

    @Transaction
    fun upsert(course: Course) {
        val id = insert(course)
        if (id == -1L) {
            update(course)
        } else {
            course.uid = id
        }
    }

    @Transaction
    fun upsert(courses: List<Course>) {
        courses.forEach { course ->
            upsert(course)
        }
    }

    @Delete
    fun delete(course: Course)

    @Delete
    fun delete(courses: List<Course>)
}

data class Semester(val year: Int, val semester: Boolean)