import { RSVPProvider } from './rsvp-provider.js'

export class RSVPComponent extends HTMLElement {
  constructor() {
    super()
    this._root = this.attachShadow({ mode: 'open' })
    const provider = this.findProvider()
    provider.addObserver(this)
  }

  connectedCallback() {}

  render() {}

  update(state) {}

  fireEvent(action, payload) {
    let evt = new CustomEvent('rsvp-event', {
      bubbles: true,
      composed: true,
      detail: { action, payload }
    })
    this.dispatchEvent(evt)
  }

  /**
   * Traverses tree upwards until a RSVPProvider node is found
   * Returns the closest provider or null if none is existent
   */
  findProvider() {
    let curNode = this
    while (curNode.parentNode) {
      curNode = curNode.parentNode
      if (curNode.host) {
        curNode = curNode.host
      }
      if (curNode instanceof RSVPProvider) {
        break
      }
    }
    return curNode instanceof RSVPProvider ? curNode : null
  }
}
