package com.nisemoe.nise.scheduler

import com.nisemoe.generated.tables.references.BEATMAPS
import com.nisemoe.nise.osu.OsuApi
import org.jooq.DSLContext
import org.slf4j.LoggerFactory
import org.springframework.context.annotation.Profile
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Service

@Service
@Profile("fix:entities")
class FixEntities(
    private val dslContext: DSLContext,
    private val osuApi: OsuApi
){

    private val logger = LoggerFactory.getLogger(javaClass)

    // TODO: Those need to be scheduled

    /**
     * This fetches all SCORES that have a beatmap_id that is not in the BEATMAPS table and tries to fetch the beatmap
     */
//    @Scheduled(fixedDelay = 120000, initialDelay = 0)
//    fun fixMissingBeatmaps() {
//
//    }

    /**
     * This fetches all BEATMAPS that have a beatmap_file that is null and tries to fetch it.
     */
    @Scheduled(cron = "0 0 0 * * *")
    fun fixBeatmapsWithoutFile() {
        val beatmapIds = dslContext.select(BEATMAPS.BEATMAP_ID)
            .from(BEATMAPS)
            .where(BEATMAPS.BEATMAP_FILE.isNull)
            .fetchInto(Int::class.java)

        this.logger.info("Found ${beatmapIds.size} beatmaps without file")

        beatmapIds.forEachIndexed { index, beatmapId ->
            val beatmap = this.osuApi.getBeatmapFile(beatmapId)

            if(beatmap != null) {
                val result = dslContext.update(BEATMAPS)
                    .set(BEATMAPS.BEATMAP_FILE, beatmap)
                    .where(BEATMAPS.BEATMAP_ID.eq(beatmapId))
                    .execute()

                this.logger.info("Updated beatmap $beatmapId, affected rows: $result [${index + 1}/${beatmapIds.size}]")
            } else {
                this.logger.error("Failed to fetch beatmap $beatmapId")
            }
        }
    }

}