<?php
namespace boru\boruai\Openai\Api\Responses;

use boru\boruai\Openai\Models\Content;

class AssistantResponse  implements \Iterator {
    /** @var \boru\boruai\Openai\Api\Responses\Parts\Message[] */
    private $messageParts = [];
    private $index = 0;
    public function __construct($result=null) {
        if($result === null) {
            throw new \Exception("AssistantResponse must be an array or Content object: null");
            return;
        }
        if($result instanceof Content) {
            $result = $result->toArray();
        }
        if(!is_array($result)) {
            throw new \Exception("AssistantResponse must be an array or Content object: ".gettype($result)." ".json_encode($result,JSON_PRETTY_PRINT));
        }
        foreach($result as $message) {
            $this->messageParts[] = new \boru\boruai\Openai\Api\Responses\Parts\Message($message);
        }
    }

    public function value() {
        $value = "";
        foreach($this->messageParts as $message) {
            $value .= $message->value();
        }
        return $value;
    }

    public function current() {
        if(isset($this->messageParts[$this->index])) {
            return $this->messageParts[$this->index];
        }
        return false;
    }

    public function next() {
        $this->index++;
    }

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

    public function valid() {
        return isset($this->messageParts[$this->index]);
    }

    public function rewind() {
        $this->index = 0;
    }
}