import type { Intent, IntentResult } from '../core/ActivityManager.js'
import { EventTypes } from './EventTypes.js'

export interface ActivityDetail {
  intent: Intent
}

export interface ActivityWithResultDetail {
  intent: Intent
  onResult(result: IntentResult, intent: Intent): void
}

export default {
  /**
   * Starts an activity with the given intent.
   * The started activity does not expect a result.
   * @param intent The intent to start.
   * @param target Optional events target on which to dispatch the event.
   */
  startActivity: (intent: Intent, target: EventTarget = document.body): void => {
    const e = new CustomEvent<ActivityDetail>(EventTypes.Intent.startActivity, {
      bubbles: true,
      cancelable: true,
      composed: true,
      detail: {
        intent,
      },
    })
    target.dispatchEvent(e)
  },

  /**
   * Starts an activity with the given intent.
   * The started activity expects a result.
   * @param intent The intent to start.
   * @param target Optional events target on which to dispatch the event.
   */
  startActivityForResult: (
    intent: Intent,
    onResult: (result: IntentResult, intent: Intent) => void,
    target: EventTarget = document.body
  ): void => {
    const e = new CustomEvent<ActivityWithResultDetail>(EventTypes.Intent.startActivityForResult, {
      bubbles: true,
      cancelable: true,
      composed: true,
      detail: {
        intent,
        onResult,
      },
    })
    target.dispatchEvent(e)
  },
}
