class Store {
  constructor(screen) {
    this.state = {}
    this._screen = screen
  }

  patchState(name, value) {
    if (this.state[name] !== value) {
      this.state[name] = value
      this.broadcast(name, { name: value })
    }
  }

  get(name) {
    return this.state[name]
  }

  remove(name) {
    delete this.state[name]
    this.broadcast(name, { name: undefined })
  }

  removeAll() {
    for (let name in this.state) {
      this.remove(name)
    }
  }

  broadcast(type, data) {
    let eventHub = function(components) {
      for (let id in components) {
        components[id].fire(type, data)
        if (components[id].components) {
          eventHub(components[id].components)
        }
      }
    }
    eventHub(this._screen.getComponents())
  }
}

export default Store
