module Dingo.Internal.Event
       ( onEvent
       , emitEvent
       ) where

import Dingo.Internal.Base (Command(..))
import Dingo.Internal.EventTypes (Event(..))
import Dingo.Internal.WidgetTypes (Widget(..))
import Dingo.Internal.Callback (CallbackM, addCommand, registerCallback)
import Dingo.Selector (ToSelector(..))

-- | Emit an event notification for a widget. This function behaves
-- exactly as if the event had occurred in the browser.
emitEvent :: Widget w s => w -> Event -> CallbackM ()
emitEvent w e =
  -- This is a little weird, but we kind of have to round-trip
  -- to ensure that all our client-side attached handlers are "in sync".
  addCommand $ TriggerEvent (getWidgetId w) e

-- | Perform a callback when the given event triggers.
onEvent :: ToSelector a => a -> Event -> CallbackM () -> CallbackM ()
onEvent s e callback = do
  callbackId <- registerCallback callback
  addCommand $ CallbackBySelector e (toSelector s) callbackId