import { RSVPComponent } from './rsvp-component.js'

class RSVPButton extends RSVPComponent {
  constructor() {
    super()
    const btn = document.createElement('button')
    const slot = document.createElement('slot')

    btn.addEventListener('click', this.handleClick.bind(this))
    btn.appendChild(slot)
    this._root.appendChild(btn)
  }

  handleClick(e) {
    this.fireEvent(this.getAttribute('action'))
  }
}

window.customElements.define('rsvp-button', RSVPButton)

class RSVPControls extends HTMLElement {
  constructor() {
    super()
    const shadow = this.attachShadow({ mode: 'open' })
    // const shadow = document.createElement('div')
    shadow.innerHTML = `
      <rsvp-button action="prevSentence">&lt;&lt;</rsvp-button>
      <rsvp-button action="prevWord">&lt;</rsvp-button>
      <rsvp-button action="stop">stop</rsvp-button>
      <rsvp-button action="playpause">start</rsvp-button>
      <rsvp-button action="nextWord">&gt;</rsvp-button>
      <rsvp-button action="nextSentence">&gt;&gt;</rsvp-button>
    `
    this._root = shadow
    // this.appendChild(shadow)
  }

  connectedCallback() {
    for (let button of this._root.querySelectorAll('button')) {
      button.addEventListener('click', e => {
        let action = e.target.getAttribute('action')
        let evt = new CustomEvent('control-event', {
          bubbles: true,
          composed: true,
          detail: { action }
        })
        this.dispatchEvent(evt)
      })
    }
  }

  updateUI(chapter, player) {
    // this.getButton('prevSentence').disabled = !chapter.hasPrevSentence()
    // this.getButton('prevWord').disabled = !chapter.hasPrevWord()
    // this.getButton('nextWord').disabled = !chapter.hasNextWord()
    // this.getButton('nextSentence').disabled = !chapter.hasNextSentence()
    // this.getButton('playpause').innerText = player.playing ? 'pause' : 'start'
  }

  getButton(name) {
    for (let btn of this._root.querySelectorAll('button')) {
      if (btn.getAttribute('action') === name) {
        return btn
      }
    }
    return null
  }
}

window.customElements.define('rsvp-controls', RSVPControls)
