package ac.mdiq.podcini.storage.database

import ac.mdiq.podcini.storage.model.DownloadResult
import ac.mdiq.podcini.utils.Logd
import kotlinx.coroutines.Job

private const val TAG: String = "LogsAndStats"

fun getFeedDownloadLog(feedId: Long): List<DownloadResult> {
    Logd(TAG, "getFeedDownloadLog() called with: $feedId")
    val dlog = realm.query(DownloadResult::class).query("feedfileId == $0", feedId).find().toMutableList()
    dlog.sortWith(DownloadResultComparator())
    return realm.copyFromRealm(dlog)
}

fun addDownloadStatus(status: DownloadResult?): Job {
    Logd(TAG, "addDownloadStatus called")
    return runOnIOScope {
        if (status != null) {
            if (status.id == 0L) status.setId()
            upsert(status) {}
//            EventFlow.postEvent(FlowEvent.DownloadLogEvent())
        }
    }
}

/** Compares the completion date of two DownloadResult objects.  */
class DownloadResultComparator : Comparator<DownloadResult> {
    override fun compare(lhs: DownloadResult, rhs: DownloadResult): Int {
        return rhs.getCompletionDate().compareTo(lhs.getCompletionDate())
    }
}
