package ocelot.desktop.ui.widget.settings

import ocelot.desktop.Settings
import ocelot.desktop.geometry.{Padding2D, Size2D}
import ocelot.desktop.graphics.IconSource
import ocelot.desktop.ui.UiHandler
import ocelot.desktop.ui.widget.{Checkbox, PaddingBox, Slider}

class UISettingsTab extends SettingsTab {
  override val icon: IconSource = IconSource.SettingsUI
  override val label: String = "UI"

  override def applySettings(): Unit = {
    if (UiHandler.fullScreen != Settings.get.windowFullscreen) {
      UiHandler.fullScreen = Settings.get.windowFullscreen
    }

    if (UiHandler.scalingFactor != Settings.get.scaleFactor) {
      UiHandler.scalingFactor = Settings.get.scaleFactor
    }
  }

  children :+= new PaddingBox(new Checkbox("Pin newly opened windows",
    initialValue = Settings.get.pinNewWindows)
  {
    override def minimumSize: Size2D = Size2D(512, 24)

    override def onValueChanged(value: Boolean): Unit = {
      Settings.get.pinNewWindows = value
    }
  }, Padding2D(bottom = 8))

  children :+= new PaddingBox(new Checkbox("Fullscreen mode",
    initialValue = Settings.get.windowFullscreen)
  {
    override def minimumSize: Size2D = Size2D(512, 24)

    override def onValueChanged(value: Boolean): Unit = {
      Settings.get.windowFullscreen = value
      applySettings()
    }
  }, Padding2D(bottom = 8))

  children :+= new PaddingBox(new Checkbox("Save workspace on exit",
    initialValue = Settings.get.saveOnExit) {
    override def minimumSize: Size2D = Size2D(512, 24)

    override def onValueChanged(value: Boolean): Unit = {
      Settings.get.saveOnExit = value
    }
  }, Padding2D(bottom = 8))

  children :+= new PaddingBox(new Checkbox("Re-open last workspace on startup",
    initialValue = Settings.get.openLastWorkspace) {
    override def minimumSize: Size2D = Size2D(512, 24)

    override def onValueChanged(value: Boolean): Unit = {
      Settings.get.openLastWorkspace = value
    }
  }, Padding2D(bottom = 8))

  children :+= new PaddingBox(new Checkbox("Show previews on screen blocks",
    initialValue = Settings.get.renderScreenDataOnNodes) {
    override def minimumSize: Size2D = Size2D(512, 24)

    override def onValueChanged(value: Boolean): Unit = {
      Settings.get.renderScreenDataOnNodes = value
    }
  }, Padding2D(bottom = 8))

  children :+= new PaddingBox(new Slider((Settings.get.scaleFactor - 1) / 2, "Interface scale", 5) {
    override def minimumSize: Size2D = Size2D(512, 24)

    // Interpolates [0; 1] as [1; 3] rounded to nearest 0.5
    private def convertToScale(slider: Float): Float = (slider * 4 + 2).round.max(2).min(6) / 2.0f

    override def formatText: String = f"$text: ${convertToScale(value)}%.1fx"

    override def onValueFinal(value: Float): Unit = {
      Settings.get.scaleFactor = convertToScale(value)
      applySettings()
    }
  }, Padding2D(bottom = 8))
}
