package net.taehui.twilight.system

import com.fasterxml.jackson.databind.ObjectMapper
import net.taehui.twilight.Logger
import net.taehui.twilight.TwilightComponent
import org.apache.commons.io.FilenameUtils
import java.io.IOException
import java.nio.file.Files
import java.util.*

object VoteSystem : Logger {
    class VoteItem : Comparable<VoteItem> {
        var title = ""
        var artist = ""
        var genre = ""
        var www = ""

        @JvmField
        var isFavorite = false

        override fun compareTo(other: VoteItem): Int {
            val isFavoriteData = other.isFavorite.compareTo(isFavorite)
            return if (isFavoriteData != 0) {
                isFavoriteData
            } else title.compareTo(other.title)
        }
    }

    private val voteItemMap = TreeMap<String, Array<VoteItem>>()
    var isLoading = false

    fun loadVote() {
        isLoading = true
        try {
            val jm = ObjectMapper()
            voteItemMap.clear()
            Files.list(TwilightComponent.VOTE_ENTRY_PATH).use {
                it.forEach { voteFilePath ->
                    val voteItems = jm.readValue(voteFilePath.toFile(), Array<VoteItem>::class.java)
                    Arrays.sort(voteItems)
                    voteItemMap[FilenameUtils.removeExtension(voteFilePath.fileName.toString())] = voteItems
                    logInfo("Loaded Vote (${voteFilePath.fileName})")

                    jm.writerWithDefaultPrettyPrinter().writeValue(voteFilePath.toFile(), voteItems)
                    logInfo("Saved Vote (${voteFilePath.fileName})")
                }
            }
        } catch (e: IOException) {
            logFault(e)
        } finally {
            isLoading = false
        }
    }

    val voteNames: List<String>
        get() {
            val voteNames = voteItemMap.keys.filter { it != "etc." }.toMutableList()
            voteNames.add("etc.")
            return voteNames
        }

    fun getVoteItems(voteName: String): Array<VoteItem>? {
        return voteItemMap[voteName]
    }
}