export class StateProvider extends HTMLElement {
  constructor() {
    super()
    this.appendChild(document.createElement('slot'))
    this.observers = []
  }

  connectedCallback() {
    this.value = this.getAttribute('value')
  }

  get name() {
    return this.getAttribute('name')
  }

  get value() {
    return this._val
  }

  set value(newValue) {
    // if (this.value !== newValue) {
    this._val = newValue
    this.notifyObservers()
    // }
  }

  static get observedAttributes() {
    return ['value']
  }

  attributeChangedCallback(name, oldValue, newValue) {
    // console.log('attrChange', name, oldValue, newValue)
    if (name === 'value') {
      this.value = newValue
    }
  }

  notifyObservers() {
    for (let obs of this.observers) {
      obs.update(this)
    }
  }

  addObserver(obs) {
    this.observers.push(obs)
  }

  removeObserver(obs) {
    this.observers = this.observers.filter(el => el !== obs)
  }
}

window.customElements.define('state-provider', StateProvider)
