package dev.fyloz.plannervio.core.service

import com.beust.klaxon.Klaxon
import com.jfoenix.svg.SVGGlyph
import javafx.scene.paint.Color
import mu.KotlinLogging
import tornadofx.SVGIcon

private val logger = KotlinLogging.logger { }
private val storedSvgPaths: List<SvgPath> = loadSvgPaths()

fun svgGlyph(pathName: SvgPathName, size: Double = 16.0, color: Color = Color.BLACK): SVGGlyph? {
    val svgPath = svgPath(pathName) ?: return null
    val glyph = SVGGlyph(svgPath.path, color)
    glyph.setSize(size, size)
    return glyph
}

private fun loadSvgPaths(): List<SvgPath> {
    val doc = SvgPath::class.java.getResource("/images/icons.json").readText()
    return Klaxon().parseArray(doc) ?: throw IllegalStateException("Could not load svg paths.")
}

private fun svgPath(pathName: SvgPathName): SvgPath? {
    val svgPath = storedSvgPaths.firstOrNull {
        pathName.pathName == it.name
    }
    if (svgPath == null) {
        logger.warn("Svg path ${pathName.pathName} not loaded or not found")
    }
    return svgPath
}

private data class SvgPath(val name: String, val path: String)

enum class SvgPathName(val pathName: String) {
    FORMAT_LIST_BULLETED("format_list_bulleted"),
    STAR("star"),
    HISTORY("history"),
    COG("cog")
}
