package com.nisemoe.nise.scheduler

import com.nisemoe.generated.tables.references.BEATMAPS
import org.jooq.DSLContext
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Profile
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Service
import java.io.File

@Profile("fix:migrate")
@Service
class FixMigration(
    private val dslContext: DSLContext
){

    @Value("\${BEATMAPS_PATH}")
    private lateinit var beatmapPath: String

    private val logger = LoggerFactory.getLogger(javaClass)

    @Scheduled(fixedDelay = 120000, initialDelay = 0)
    fun fixStuff() {
        val dir = File(beatmapPath)

        val regex = Regex("(.+) - (.+) \\((.+)\\)\\[(.+)\\]\\.osu")

        if (dir.exists() && dir.isDirectory) {
            dir.listFiles()?.forEach { file ->
                val matchResult = regex.matchEntire(file.name)
                if (matchResult != null) {
                    val (artist, title, creator, version) = matchResult.destructured
                    val content = file.readText()

                    val result = dslContext.update(BEATMAPS)
                        .set(BEATMAPS.BEATMAP_FILE, content)
                        .where(BEATMAPS.ARTIST.eq(artist))
                        .and(BEATMAPS.TITLE.eq(title))
                        .and(BEATMAPS.CREATOR.eq(creator))
                        .and(BEATMAPS.VERSION.eq(version))
                        .execute()

                    this.logger.info("Artist: $artist, Title: $title, Creator: $creator, Version: $version")
                    this.logger.info("Affected rows: $result")
                }
            }
        } else {
            this.logger.error("Directory does not exist or is not a directory")
        }
    }

}