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

use boru\dhutils\traits\GetSetArray;
use boru\dhttp\core\Response;

class ApiBaseResponse implements \JsonSerializable, \ArrayAccess {
    use GetSetArray;
    /**
     * @var \boru\dhutils\http\Response
     */
    protected $response;

    protected $body = [];

    /**
     * @param \boru\dhutils\http\Response|array $response
     */
    public function __construct($response) {
        $this->setGetSetMainArray("body");
        if(is_array($response)) {
            $this->body = $response;
        } elseif($response instanceof Response) {
            $this->response = $response;
            $this->body = $response->body(true);
        }
        if(isset($this->body["error"])) {
            throw new ApiException($this->body["error"]);
        }
    }

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

    public function __set($field,$val) {
        $this->set($field,$val);
    }

    /**
     * @param Response $response
     */
    public static function fromResponse($resp) {
        if($resp instanceof Response) {
            return new static($resp);
        }
        return false;
    }

    public static function fromArray($array) {
        if(!is_array($array) && !is_object($array)) {
            $array = json_decode($array,true);
            if(!$array) {
                return false;
            }
        }
        return new static($array);
    }

    /**
     * Inherits trait functions from GetSetArray
     * ->get($key,$default=null)
     * ->set($key,$val='',$append=false)
     * ->exists($key=null)
     */

     public function jsonSerialize($array=null) {
        if(is_null($array)) {
            $array = $this->body;
        }
        return $array;
    }

    /**
     * Ignore intelephense error, php 5.6 :(
     */
    public function offsetExists($offset) {
        return $this->exists($offset);
    }

    /**
     * Ignore intelephense error, php 5.6 :(
     */
    public function offsetGet($offset) {
        return $this->get($offset);
    }

    /**
     * Ignore intelephense error, php 5.6 :(
     */
    public function offsetSet($offset , $value) {
        $this->set($offset,$value);
    }

    /**
     * Ignore intelephense error, php 5.6 :(
     */
    public function offsetUnset($offset) {
        $this->remove($this->$offset);
    }

    public function __toString() {
        return json_encode($this);
    }
}