<?php
namespace boru\boruai\Models\Services;

use boru\boruai\Models\Response;

class OpenAIResponseService implements ServiceInterface {
    /** @var Response */
    private $responseObject;

    public function __construct($responseObject=null) {
        $this->responseObject = $responseObject;
        if(!$this->responseObject) {
            $this->responseObject = new Response();
        }
    }

    public function isStreamable() {
        return true;
    }

    public function call($options=[]) {
        $input = isset($options["input"]) ? $options["input"] : null;
        $callback = isset($options["callback"]) ? $options["callback"] : null;
        $stream = isset($options["stream"]) ? $options["stream"] : false;
        echo json_encode($this->responseObject->forInput(), JSON_PRETTY_PRINT);
        //exit();
        $result = $this->responseObject->create($input, $callback, $stream);
        if($result) {
            $this->responseObject = $result;
            return $result->getResult()."\n";
        }
        return false;
    }

    public function callback($callback = null) {
        $this->responseObject->callback($callback);
    }

    public function model($model=null) {
        return $this->responseObject->model($model);
    }

    public function set($k,$value=null) {
        if(method_exists($this->responseObject, $k)) {
            call_user_func([$this->responseObject, $k], $value);
        }
    }

    public function get($k=null,$default=null) {
        if(method_exists($this->responseObject, $k)) {
            $value = call_user_func([$this->responseObject, $k]);
            if($value) {
                return $value;
            }
        }
        return $default;
    }

    public function addTool($tool=[]) {
        return $this->responseObject->addTool($tool);
    }

    public function addTools($tools=[]) {
        return $this->responseObject->addTools($tools);
    }

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

    public function addMessage($message,$options=[]) {
        $newMessage = isset($options["newMessage"]) ? $options["newMessage"] : false;
        $newMessage = $newMessage ? true : false;

        $prependFirstMessage = isset($options["prependFirstMessage"]) ? $options["prependFirstMessage"] : false;
        $prependFirstMessage = $prependFirstMessage ? true : false;

        return $this->responseObject->addMessage($message, $newMessage, $prependFirstMessage);
    }

    public function addImage($image,$options=[]) {
        $detail = isset($options["detail"]) ? $options["detail"] : null;
        return $this->responseObject->addImage($image, $detail);
    }

    public function addFile($file,$options=[]) {
        return $this->responseObject->addFile($file);
    }
    
    public function setEventDispatcher($dispatcher) {
        $this->responseObject->setEventDispatcher($dispatcher);
    }
}