package ocelot.desktop.windows

import com.github.sarxos.webcam.Webcam
import ocelot.desktop.entity.Camera
import ocelot.desktop.geometry.{Padding2D, Size2D, Vector2D}
import ocelot.desktop.node.nodes.CameraNode
import ocelot.desktop.ui.layout.{Layout, LinearLayout}
import ocelot.desktop.ui.widget._
import ocelot.desktop.ui.widget.contextmenu.{ContextMenu, ContextMenuEntry}
import ocelot.desktop.ui.widget.window.PanelWindow
import ocelot.desktop.util.{Orientation, WebcamCapture}

import scala.jdk.CollectionConverters.CollectionHasAsScala

class CameraWindow(cameraNode: CameraNode) extends PanelWindow {
  def camera: Camera = cameraNode.camera

  override protected def title: String = s"Camera ${cameraNode.label.get}"
  override protected def titleMaxLength: Int = 36

  setInner(new Widget {
    override protected val layout: Layout = new LinearLayout(this, orientation = Orientation.Vertical)

    children :+= new PaddingBox(
      new Button {
        override def minimumSize: Size2D = super.minimumSize.copy(width = 256)
        override def maximumSize: Size2D = super.maximumSize.copy(width = 512)
        override def text: String = camera.webcamCapture.map(_.name).getOrElse("<No webcam available>")

        override def onClick(): Unit = {
          val menu = new ContextMenu
          for (webcam <- Webcam.getWebcams().asScala) {
            menu.addEntry(ContextMenuEntry(webcam.getName) {
              cameraNode.camera.webcamCapture = WebcamCapture.getInstance(webcam)
            })
          }

          root.get.contextMenus.open(menu, Vector2D(position.x, position.y + size.height))
        }
      },
      Padding2D.equal(8),
    )

    children :+= new PaddingBox(
      new Checkbox("Flip image horizontally",
        initialValue = camera.flipHorizontally) {
        override def onValueChanged(newValue: Boolean): Unit = camera.flipHorizontally = newValue
      },
      Padding2D.equal(8),
    )

    children :+= new PaddingBox(
      new Checkbox("Flip image vertically",
        initialValue = camera.flipVertically) {
        override def onValueChanged(newValue: Boolean): Unit = camera.flipVertically = newValue
      },
      Padding2D.equal(8),
    )

    children :+= new PaddingBox(
      new Checkbox("Unlimit call budget",
        initialValue = camera.directCalls) {
        override def onValueChanged(newValue: Boolean): Unit = camera.directCalls = newValue
      },
      Padding2D.equal(8),
    )
  })
}
