package ocelot.desktop.ui.widget

import ocelot.desktop.ui.event.Event

import scala.collection.mutable.ListBuffer

class EventHandlers extends PartialFunction[Event, Unit] {
  private val handlers = new ListBuffer[EventHandler]

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

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

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

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

      if (handler.isDefinedAt(event)) {
        handler(event)
      }
    }
  }

  type EventHandler = PartialFunction[Event, Unit]
}
