<?php

namespace App\Classes\Modules\Documents\DataTransferObjects;

use App\Classes\Exceptions\MalformedRequestException;
use App\Classes\General\Interfaces\DataTransferObject;
use App\Classes\ValueObjects\Constants\FileType;
use Illuminate\Support\Str;
use Intervention\Image\ImageManager;

class FileObject implements DataTransferObject
{
    /** @var string */
    private $data;

    /**
     * FileInfoObject constructor.
     * @param string $data
     */
    public function __construct(string $data)
    {
        $this->data = $data;
    }

    /**
     * @return \Intervention\Image\Image|string
     * @throws MalformedRequestException
     */
    public function getData()
    {
        return $this->getExtension() === 'pdf' ? $this->data : (new imageManager())->make($this->data);
    }

    /**
     * @return string
     */
    public function getFileName(): string
    {
        return (string) Str::uuid();
    }

    /**
     * @return string
     */
    public function getMimeType(): string
    {
        return finfo_file(finfo_open(), $this->data, FILEINFO_MIME_TYPE);
    }

    /**
     * @return string
     * @throws MalformedRequestException
     */
    public function getExtension(): string
    {
        if(array_key_exists($this->getMimeType(), FileType::EXTENSION)){
            return FileType::EXTENSION[$this->getMimeType()];
        }

        throw new MalformedRequestException('Failed to save file due to Unknown file extension');
    }

    /**
     * @return string
     * @throws MalformedRequestException
     */
    public function getDecodedData(): string
    {
        return $this->getExtension() === 'pdf' ?
            base64_decode((explode('base64,', $this->getData()))[1]):
            $this->getData()->encode('data-url')->encoded;
    }

    /**
     * @param string $data
     */
    public function setData(string $data): void
    {
        $this->data = $data;
    }





}