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 voteNameVoteItemsMap = TreeMap<String, Array<VoteItem>> { o1, o2 ->
        if (o1 == "etc.") {
            if (o2 == "etc.") {
                0
            } else {
                1
            }
        } else if (o2 == "etc.") {
            -1
        } else {
            o1.compareTo(o2)
        }
    }
    var isLoading = false

    fun loadVote() {
        isLoading = true
        try {
            val jm = ObjectMapper()
            voteNameVoteItemsMap.clear()
            Files.list(TwilightComponent.VOTE_ENTRY_PATH).use {
                it.forEach { voteFilePath ->
                    val voteItems = jm.readValue(voteFilePath.toFile(), Array<VoteItem>::class.java)
                    Arrays.sort(voteItems)
                    voteNameVoteItemsMap[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: Set<String>
        get() {
            return voteNameVoteItemsMap.keys
        }

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