import { Listenable } from '../Listenable'
import { Listener } from '../Listener'
import { Component } from '../component'

export type IOToggleEvent = boolean

export function makeToggleListener(
  listener: (data: IOToggleEvent, _event: ToggleEvent) => void
): Listener {
  return (component) => {
    return listenToggle(component, (event, _event) => {
      listener(event, _event)
    })
  }
}

export function listenToggle(
  component: Listenable,
  onWheel: (event: IOToggleEvent, _event: ToggleEvent) => void
): () => void {
  const { $element } = component as Component<HTMLElement>

  const toggleListener = (_event: ToggleEvent) => {
    const { oldState, newState } = _event

    if (newState !== oldState) {
      const shown = newState === 'open' ? true : false

      onWheel(shown, _event)
    }
  }

  $element.addEventListener('toggle', toggleListener, { passive: false })
  return () => {
    $element.removeEventListener('toggle', toggleListener)
  }
}
