package ocelot.desktop.ui.widget

import ocelot.desktop.ui.event.{Dispatchable, Event}

import scala.collection.mutable.ArrayBuffer

class EventHandlers extends PartialFunction[Dispatchable, Unit] {
  private val handlers = ArrayBuffer.empty[EventHandler]

  def +=(handler: EventHandler): Unit = handlers += handler

  def -=(handler: EventHandler): Unit = handlers -= handler

  override def isDefinedAt(event: Dispatchable): Boolean = handlers.exists(_.isDefinedAt(event))

  override def apply(event: Dispatchable): Unit = {
    for (handler <- handlers) {
      if (event.consumed) {
        return
      }

      handler.applyOrElse(event, (_: Dispatchable) => ())
    }
  }

  type EventHandler = PartialFunction[Dispatchable, Unit]
}
