package com.all.pdfreader.pro.app.room.dao

import androidx.room.*
import com.all.pdfreader.pro.app.room.entity.PdfDocumentEntity
import kotlinx.coroutines.flow.Flow

@Dao
interface PdfDocumentDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertOrUpdate(document: PdfDocumentEntity)

    //@Update 不会响应flow
    @Update
    suspend fun update(document: PdfDocumentEntity)

    @Query("SELECT * FROM pdf_documents WHERE fileHash = :fileHash")
    suspend fun getByHash(fileHash: String): PdfDocumentEntity?

    @Query("SELECT * FROM pdf_documents WHERE filePath = :filePath")
    suspend fun getByPath(filePath: String): PdfDocumentEntity?

    @Query("SELECT * FROM pdf_documents WHERE isFavorite = 1 ORDER BY addedToFavoriteTime DESC")
    fun getFavoriteDocuments(): Flow<List<PdfDocumentEntity>>

    @Query("""SELECT * FROM pdf_documents WHERE :query != '' AND TRIM(:query) != ''  AND LOWER(fileName) LIKE '%' || LOWER(:query) || '%' """)
    fun searchDocuments(query: String): Flow<List<PdfDocumentEntity>>

    @Query("SELECT * FROM pdf_documents ORDER BY lastOpenedTime DESC")
    fun getAllDocuments(): Flow<List<PdfDocumentEntity>>

    @Query("SELECT * FROM pdf_documents WHERE lastOpenedTime > 0 ORDER BY lastOpenedTime DESC")
    fun getRecentlyOpenedDocuments(): Flow<List<PdfDocumentEntity>>

    @Query("SELECT * FROM pdf_documents ORDER BY lastOpenedTime DESC")
    suspend fun getAllDocumentsOnce(): List<PdfDocumentEntity>

    @Delete
    suspend fun delete(document: PdfDocumentEntity)

    @Query("DELETE FROM pdf_documents WHERE filePath = :filePath")
    suspend fun deleteByPath(filePath: String)

    // 批量删除
    @Query("DELETE FROM pdf_documents WHERE filePath IN (:filePaths)")
    suspend fun deleteByPaths(filePaths: List<String>)

    // 批量取消收藏，设置isFavorite = 0
    @Query("UPDATE pdf_documents SET isFavorite = 0 WHERE filePath IN (:filePaths)")
    suspend fun cancelFavoriteStatus(filePaths: List<String>)

    //@Query 会响应flow
    @Query("UPDATE pdf_documents SET filePath = :newFilePath, fileName = :newName WHERE filePath = :oldFilePath")
    suspend fun updateFilePathAndFileName(oldFilePath: String, newFilePath: String, newName: String)

    @Query("UPDATE pdf_documents SET isPassword = :hasPassword WHERE filePath = :filePath")
    suspend fun updateIsPassword(filePath: String, hasPassword: Boolean)

    @Query("UPDATE pdf_documents SET lastOpenedTime = :time WHERE filePath = :filePath")
    suspend fun updateLastOpenTime(filePath: String, time: Long)

    @Query("UPDATE pdf_documents SET lastOpenedTime = :time WHERE filePath IN (:filePaths)")
    suspend fun updateLastOpenTimes(filePaths: List<String>, time: Long)

}