<?php

namespace boru\boruai\Openai\Stream;

use boru\boruai\Openai\Stream\Contract\StreamEventDispatcherInterface;
use boru\boruai\Openai\Stream\Contract\StreamEventListenerInterface;

class SimpleStreamEventDispatcher implements StreamEventDispatcherInterface
{
    /** @var StreamEventListenerInterface[] */
    private $listeners = array();

    /** @var bool */
    private $stopOnHandled = false;

    /**
     * @param bool $stopOnHandled If true, stop dispatching to further
     *                             listeners once one returns true from handle().
     */
    public function __construct($stopOnHandled = false)
    {
        $this->stopOnHandled = $stopOnHandled ? true : false;
    }

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

    public function dispatch(StreamEvent $event)
    {
        foreach ($this->listeners as $listener) {
            $handled = $listener->handle($event);
            if ($this->stopOnHandled && $handled) {
                break;
            }
        }
    }
}
