package ocelot.desktop.ui.widget

import ocelot.desktop.ColorScheme
import ocelot.desktop.color.Color
import ocelot.desktop.graphics.Graphics

class ComponentUsageBar extends Widget with TickUpdatable {
  var maxValue = 0
  var currentValue = 0
  var title = "Component usage"

  private def drawText(g: Graphics, x: Float, y: Float, text: String): Unit = {
    g.setSmallFont()
    g.background = Color.Transparent
    g.foreground = ColorScheme("HistogramEdge")
    g.text(x - text.length * 4, y, text)
    g.setNormalFont()
  }

  override def draw(g: Graphics): Unit = {
    val marginLeft = 41
    val x = position.x + marginLeft

    val cellThickness = 2f
    val cellHeight = 11f
    // the width is calculated in this way so that it always will be in sync with the width of histograms (just to look nice)
    val gridWidth = ((width - cellThickness - marginLeft) / cellHeight).toInt * cellHeight
    val gridHeight = cellHeight
    val cellCount = Math.min((gridWidth / cellHeight).toInt, maxValue)
    val cellWidth = gridWidth / cellCount

    // Text
    drawText(g, x - marginLeft / 2 - 4, position.y + 3, currentValue.toString)
    drawText(g, x - marginLeft / 2 - 4, position.y + 18, s"($maxValue)")
    drawText(g, x + gridWidth / 2, position.y + 18, title)

    // Horizontal lines
    g.rect(x, position.y, gridWidth, cellThickness, ColorScheme("HistogramGrid"))
    g.rect(x, position.y + cellHeight, gridWidth, cellThickness, ColorScheme("HistogramGrid"))

    // Vertical lines
    for (i <- 0 until cellCount) {
      g.rect(
        x + i * cellWidth,
        position.y,
        cellThickness,
        gridHeight,
        ColorScheme("HistogramGrid"),
      )
    }

    // Closing vertical line
    g.rect(
      x + gridWidth,
      position.y,
      cellThickness,
      gridHeight + cellThickness,
      ColorScheme("HistogramGrid"),
    )

    val fillWidth = Math.min(
      if (cellCount == maxValue)
        cellWidth * currentValue - cellThickness
      else
        gridWidth * (currentValue.toFloat / maxValue),
      gridWidth,
    )

    // Value fill
    val fillColor = {
      if (currentValue == maxValue) ColorScheme("HistogramFillWarning")
      else if (currentValue > maxValue) ColorScheme("HistogramFillError")
      else ColorScheme("HistogramFill")
    }

    g.rect(
      x + cellThickness,
      position.y + cellThickness,
      fillWidth,
      cellHeight - cellThickness,
      fillColor,
    )

    // Value line
    val edgeColor = {
      if (currentValue == maxValue) ColorScheme("HistogramEdgeWarning")
      else if (currentValue > maxValue) ColorScheme("HistogramEdgeError")
      else ColorScheme("HistogramEdge")
    }

    g.rect(
      x + fillWidth + cellThickness,
      position.y,
      cellThickness,
      cellHeight + cellThickness,
      edgeColor,
    )
  }
}
