<?php
namespace boru\boruai\Openai\Response\Parts\Content;

use boru\boruai\Models\File;
use boru\boruai\Openai\Models\BaseModel;
use boru\boruai\Tools\Util;

class InputImage extends BaseModel {
    private $detail = "auto";
    private $type = "input_image";
    private $fileId;
    private $imageUrl;

    public function type($type=null) {
        if ($type) {
            $this->type = $type;
        }
        return $this->type;
    }
    public function detail($detail=null) {
        if ($detail) {
            $this->detail = $detail;
        }
        return $this->detail;
    }
    public function fileId($fileId=null) {
        if ($fileId) {
            $this->fileId = $fileId;
        }
        return $this->fileId;
    }
    public function imageUrl($imageUrl=null) {
        if ($imageUrl) {
            if(file_exists($imageUrl)) {
                $base64 = Util::makeBase64url($imageUrl);
                if($base64) {
                    $imageUrl = $base64;
                } else {
                    throw new \Exception("File not found");
                }
            }
            $this->imageUrl = $imageUrl;
        }
        return $this->imageUrl;
    }
    public function toArray() {
        $array = [
            "type" => $this->type(),
            "detail" => $this->detail(),
            "file_id" => $this->fileId(),
            "image_url" => $this->imageUrl(),
        ];
        return array_filter($array, function($value) {
            return !is_null($value);
        });
    }
    public function __toString() {
        return json_encode($this->toArray());
    }

    public function __construct($input=null) {
        if($input instanceof File) {
            if(!$input->fileId()) {
                $input->upload();
            }
            $this->fileId($input->fileId());
            return;
        }
        if(!is_array($input)) {
            if(is_string($input) && substr($input,0,5) == "file-") {
                $this->fileId($input);
                return;
            } else {
                $this->imageUrl($input);
                return;
            }
        }
        return parent::__construct($input);
    }

}