package ocelot.desktop.util

import ocelot.desktop.geometry.{Rect2D, Size2D}
import ocelot.desktop.graphics.{IconSource, Texture}

import javax.imageio.ImageIO
import scala.collection.mutable
import scala.io.Source

object Spritesheet extends Resource with Logging {
  val sprites = new mutable.HashMap[String, Rect2D]()
  var texture: Texture = _

  private var resolution: Size2D = _

  def spriteSize(sprite: String): Size2D = sprites(sprite).size * resolution

  def spriteSize(icon: IconSource): Size2D = icon.animation match {
    case Some(animation) =>
      animation.frameSize match {
        case Some(size) => size

        case None =>
          val size = spriteSize(icon.path)

          Size2D(size.width, size.width)
      }

    case None => spriteSize(icon.path)
  }

  def load(): Unit = {
    logger.info("Loading sprites...")

    val imageURL = getClass.getResource("/ocelot/desktop/images/spritesheet/spritesheet.png")
    val image = ImageIO.read(imageURL)
    texture = new Texture(image)

    resolution = Size2D(image.getWidth, image.getHeight)

    val txt = Source.fromURL(getClass.getResource("/ocelot/desktop/images/spritesheet/spritesheet.txt"))

    for (line <- txt.getLines) {
      val split = line.split("\\s+")
      sprites += (split.head -> Rect2D(
        split(1).toFloat / resolution.width,
        split(2).toFloat / resolution.height,
        split(3).toFloat / resolution.width,
        split(4).toFloat / resolution.height,
      ))
    }

    txt.close()

    logger.info(s"Loaded ${sprites.size} sprites")
  }

  override def freeResource(): Unit = {
    super.freeResource()
    texture.freeResource()
  }
}
