package ocelot.desktop

import ocelot.desktop.color.{IntColor, RGBAColorNorm}
import ocelot.desktop.util.Logging

import scala.collection.mutable
import scala.io.Source

class ColorScheme extends Logging {
  private val entries = new mutable.HashMap[String, RGBAColorNorm]()

  def apply(key: String): RGBAColorNorm = entries(key)

  def add(key: String, color: RGBAColorNorm): Unit = entries.addOne((key, color))

  def load(source: Source): Unit = {
    logger.info(s"Loading color scheme")

    val oldSize = entries.size

    for (line_ <- source.getLines) {
      val line = line_.trim
      if (!line.startsWith("#") && line.nonEmpty) {
        val split = line.split("\\s*=\\s*")
        val key = split(0)
        val value = split(1)
        if (value.startsWith("#")) {
          val bytes = java.lang.Long.parseLong(value.substring(1), 16)
          val color = if (value.length == 9) {
            val rgb = bytes >> 8
            IntColor(rgb.toInt).toRGBANorm.withAlpha((bytes & 0xff).toFloat / 255f)
          } else IntColor(bytes.toInt).toRGBANorm
          entries.addOne((key, color))
        }
      }
    }

    logger.info(s"Loaded ${entries.size - oldSize} colors")
  }
}

object ColorScheme {
  val General = new ColorScheme

  def load(source: Source): Unit = General.load(source)

  def apply(key: String): RGBAColorNorm = General(key)
}
