package ocelot.desktop.ui.widget.settings

import ocelot.desktop.{ColorScheme, Settings}
import ocelot.desktop.audio.{ClickSoundSourceFactory, SoundSource}
import ocelot.desktop.geometry.{Padding2D, Size2D}
import ocelot.desktop.graphics.Graphics
import ocelot.desktop.ui.layout.LinearLayout
import ocelot.desktop.ui.widget.modal.ModalDialog
import ocelot.desktop.ui.widget.verticalmenu.{VerticalMenu, VerticalMenuButton}
import ocelot.desktop.ui.widget.{Button, PaddingBox, Widget}
import ocelot.desktop.util.{Orientation, SettingsData}

class SettingsDialog extends ModalDialog {
  private val settingsBackup = new SettingsData(Settings.get)

  private val tabs = Seq(
    new UISettingsTab,
    new SoundSettingsTab,
    new KeymapSettingsTab,
    new SystemSettingsTab,
  )

  private def resetSettings(): Unit = {
    Settings.get.updateWith(settingsBackup)
    tabs.foreach(_.applySettings())
  }

  private val container: Widget = new Widget {
    override val layout = new LinearLayout(this, orientation = Orientation.Vertical)

    children :+= tabs.head

    children :+= new Widget {
      override val layout = new LinearLayout(this, orientation = Orientation.Horizontal)

      children :+= new Widget {
        override def maximumSize: Size2D = Size2D(Float.PositiveInfinity, 1)
      }

      children :+= new Button {
        override def text: String = "Cancel"
        override protected def clickSoundSource: ClickSoundSourceFactory = SoundSource.InterfaceClickLow
        override def onClick(): Unit = {
          resetSettings()
          close()
        }
      }

      children :+= new PaddingBox(
        new Button {
          override def text: String = "Ok"

          override def onClick(): Unit = close()
        },
        Padding2D(left = 8),
      )
    }
  }

  children :+= new PaddingBox(
    new Widget {
      override val layout = new LinearLayout(this, orientation = Orientation.Horizontal)

      children :+= new Widget {
        override val layout = new LinearLayout(this, orientation = Orientation.Vertical)

        children :+= tabs.foldLeft(new VerticalMenu())((menu, tab) => {
          menu.addEntry(new VerticalMenuButton(tab.icon, tab.label,
            self => {
              container.children = tab +: container.children.tail
              menu.entries.foreach(_.selected = false)
              self.selected = true
            }))
        })
        children.head.asInstanceOf[VerticalMenu].entries.head.selected = true
      }

      children :+= new PaddingBox(container, Padding2D(left = 8))

      override def draw(g: Graphics): Unit = {
        g.rect(bounds.x + children.head.bounds.w - 2f, bounds.y, 2f, bounds.h, ColorScheme("VerticalMenuBorder"))
        super.draw(g)
      }
    },
    Padding2D.equal(16),
  )
}
