package ocelot.desktop.ui.widget.component

import ocelot.desktop.geometry.Vector2D
import ocelot.desktop.ui.UiHandler
import ocelot.desktop.ui.event.{KeyEvent, MouseEvent}
import ocelot.desktop.ui.layout.Layout
import ocelot.desktop.ui.widget.Widget
import org.lwjgl.input.Keyboard

import scala.collection.immutable.ArraySeq

class ComponentSelectors extends Widget {
  override protected val layout: Layout = new Layout(this)

  private def selectors: ArraySeq[ComponentSelector] = children.map(_.asInstanceOf[ComponentSelector])

  override def receiveAllMouseEvents: Boolean = true

  eventHandlers += {
    case KeyEvent(KeyEvent.State.Press, Keyboard.KEY_ESCAPE, _) =>
      closeAll()

    case MouseEvent(MouseEvent.State.Press, _) =>
      if (!selectors.map(_.bounds).exists(_.contains(UiHandler.mousePosition))) closeAll()
  }

  def open(selector: ComponentSelector, openPos: Vector2D): Unit = {
    selector.position = openPos
    selector.open()
    children :+= selector
  }

  def close(selector: ComponentSelector): Unit = {
    selector.close()
  }

  def closeAll(): Unit = {
    for (child <- selectors) close(child)
  }

  override def update(): Unit = {
    super.update()
    children = children.filterNot(_.asInstanceOf[ComponentSelector].isClosed)
  }
}
