<?php
namespace boru\ai\Stream;

class StreamEventDispatcher
{
    /** @var StreamEventListenerInterface[] */
    protected $listeners = array();

    /** @var callable[] */
    protected $callbacks = array();

    public function addListener(StreamEventListenerInterface $listener)
    {
        $this->listeners[] = $listener;
        return $this;
    }

    public function listeners()
    {
        return $this->listeners;
    }

    public function addCallback($callback)
    {
        if (!is_callable($callback)) {
            throw new \InvalidArgumentException('Event callback must be callable');
        }
        $this->callbacks[] = $callback;
        return $this;
    }

    public function callbacks()
    {
        return $this->callbacks;
    }

    public function dispatch(StreamEvent $event)
    {
        foreach ($this->listeners as $listener) {
            $listener->handle($event);
        }

        foreach ($this->callbacks as $callback) {
            call_user_func($callback, $event);
        }

        return $this;
    }
}
