package ocelot.desktop.ui.widget.settings

import ocelot.desktop.color.Color
import ocelot.desktop.{ColorScheme, Settings}
import ocelot.desktop.geometry.{Padding2D, Size2D}
import ocelot.desktop.graphics.IconSource
import ocelot.desktop.ui.event.KeyEvent
import ocelot.desktop.ui.layout.LinearLayout
import ocelot.desktop.ui.widget.{Button, Label, PaddingBox, Widget}
import ocelot.desktop.util.Keybind.Keybind
import ocelot.desktop.util.{Keybind, Orientation}
import org.lwjgl.input.Keyboard


class KeymapSettingsTab extends SettingsTab {
  override val layout = new LinearLayout(this, orientation = Orientation.Vertical, gap = 8)

  override val icon: IconSource = IconSource.Icons.SettingsKeymap
  override val label: String = "Keymap"

  private def section(title: String, keybinds: Seq[Keybind]): Widget = new PaddingBox(new Widget {
    override val layout = new LinearLayout(this, orientation = Orientation.Vertical)

    override def maximumSize: Size2D = minimumSize.copy(width = 257)

    children :+= new PaddingBox(new Label(title, small = true) {
      override def maximumSize: Size2D = minimumSize
      override def color: Color = ColorScheme("LabelDisabled")
    }, Padding2D(top = 4, bottom = 8))

    keybinds.foreach(keybind => {
      children :+= new PaddingBox(new Widget {
        children :+= new PaddingBox(new Label(keybind.description), Padding2D(top = 4, right = 8))
        children :+= new Button {
          private var listening: Boolean = false

          eventHandlers += {
            case KeyEvent(KeyEvent.State.Release, code, _) if listening =>
              Settings.get.keymap.set(keybind, code)
              listening = false
          }

          override def text: String = if (listening) "..." else Keyboard.getKeyName(Settings.get.keymap(keybind))
          override def onClick(): Unit = {
            listening = !listening
          }
        }
      }, Padding2D(bottom = 4))
    })
  }, Padding2D(bottom = 8))

  children :+= new PaddingBox(new Widget {
    children :+= new Widget {
      override val layout = new LinearLayout(this, orientation = Orientation.Vertical)
      children :+= section("OpenComputers", Seq(
        Keybind.Insert,
      ))
      children :+= section("Ocelot", Seq(
        Keybind.UIDebug,
        Keybind.FPSCounter,
        Keybind.ReloadWorkspace,
        Keybind.Profiler,
        Keybind.Fullscreen,
      ))
    }
    children :+= new Widget {
      override def maximumSize: Size2D = Size2D(16, 8)
    }
    children :+= section("Workspace", Seq(
      Keybind.Center,
      Keybind.QuickSave,
      Keybind.QuickLoad,
      Keybind.Screenshot,
      Keybind.PauseEmulation,
    ))
  }, Padding2D(bottom = 8))
}
