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

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

class InputFile extends BaseModel {
    private $type = "input_file";
    private $fileId;
    private $fileData;
    private $filename;

    public function type($type=null) {
        if ($type) {
            $this->type = $type;
        }
        return $this->type;
    }
    public function fileId($fileId=null) {
        if ($fileId) {
            $this->fileId = $fileId;
        }
        return $this->fileId;
    }
    public function fileData($fileData=null,$read=true) {
        if ($fileData) {
            if($read && file_exists($fileData)) {
                $base64 = Util::makeBase64url($fileData);
                $fileName = basename($fileData);
                if($base64) {
                    $fileData = $base64;
                    $this->filename($fileName,false);
                } else {
                    throw new \Exception("File not found");
                }
            }
            $this->fileData = $fileData;
        }
        return $this->fileData;
    }
    public function filename($filename=null,$read=true) {
        if ($filename) {
            if($read && file_exists($filename)) {
                $base64 = Util::makeBase64url($filename);
                if($base64) {
                    $this->fileData($base64,false);
                    $filename = basename($filename);
                } else {
                    throw new \Exception("File not found");
                }
            }
            $this->filename = $filename;
        }
        return $this->filename;
    }
    public function toArray() {
        $array = [
            "type" => $this->type(),
            "file_id" => $this->fileId(),
            "file_data" => $this->fileData(),
            "filename" => $this->filename(),
        ];
        return array_filter($array, function($value) {
            return !is_null($value);
        });
    }
    public function __toString() {
        return json_encode($this->toArray());
    }

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