package com.nisemoe.nise.scheduler

import com.nisemoe.nise.SimilarReplayEntry
import com.nisemoe.nise.Statistics
import com.nisemoe.nise.SuspiciousScoreEntry
import com.nisemoe.nise.database.ScoreService
import com.nisemoe.nise.database.StatisticsService
import com.nisemoe.nise.rss.RssFeed
import com.nisemoe.nise.rss.RssService
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import org.slf4j.LoggerFactory
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Service
import org.springframework.util.StopWatch
import kotlin.math.roundToInt

@Service
class GlobalCache(
    private val scoreService: ScoreService,
    private val statisticsService: StatisticsService,
    private val rssService: RssService
) {

    private val logger = LoggerFactory.getLogger(javaClass)

    var similarReplays: List<SimilarReplayEntry>? = null
    var suspiciousScores: List<SuspiciousScoreEntry>? = null
    var statistics: Statistics? = null
    var rssFeed: RssFeed? = null

    // 10 minutes to ms = 600000
    @Scheduled(fixedDelay = 600000, initialDelay = 0)
    fun updateCaches() {
        val stopwatch = StopWatch()
        stopwatch.start()
        logger.info("Updating the cache!")

        runBlocking {
            val rssFeedDeferred = async { rssService.generateFeed() }
            val statisticsDeferred = async { statisticsService.getStatistics() }
            val similarReplaysDeferred = async { scoreService.getSimilarReplays() }
            val suspiciousScoresDeferred = async { scoreService.getSuspiciousScores() }

            rssFeed = rssFeedDeferred.await()
            statistics = statisticsDeferred.await()
            similarReplays = similarReplaysDeferred.await()
            suspiciousScores = suspiciousScoresDeferred.await()
        }

        stopwatch.stop()
        logger.info("Cache updated in {} seconds", String.format("%.2f", stopwatch.totalTimeSeconds))
    }

}