<?php

namespace Zoomyboy\MedialibraryHelper;

use Symfony\Component\HttpFoundation\File\File;

class MediaFile
{

    public File $file;

    public function __construct(string $path)
    {
        $this->file = new File($path, false);
    }

    public function getBasename(): string
    {
        return $this->file->getBasename('.' . $this->file->getExtension());
    }

    public function setBasename(string $basename): void
    {
        $newInstance = new self(($this->getPath() ? $this->getPath() . '/' : '') . $basename . '.' . $this->getExtension());
        $this->file = $newInstance->file;
    }

    public function setExtension(string $extension): void
    {
        $newInstance = new self(($this->getPath() ? $this->getPath() . '/' : '') . $this->getBasename() . '.' . $extension);
        $this->file = $newInstance->file;
    }

    public function __call($method, $arguments)
    {
        return $this->file->{$method}(...$arguments);
    }

    public static function extensionFromData(string $data): string
    {
        $tempFile = sys_get_temp_dir() . '/' . str()->uuid()->toString();

        file_put_contents($tempFile, base64_decode($data));

        $extension = (new self($tempFile))->guessExtension();

        unlink($tempFile);

        return $extension;
    }
}
