<?php

namespace App\Helpers;

use Illuminate\Http\File;
use Illuminate\Http\UploadedFile;

class FileHelper
{
    public static function getQueuePath($queueUid)
    {
        $path = join(DIRECTORY_SEPARATOR, [
            dirname(dirname(__DIR__)),
            'storage',
            'app',
            'analysis-queue',
            str_replace(['.', '/', '\\'], '', $queueUid)
        ]);

        if (!file_exists($path))
        {
            mkdir($path, 0755, true);
        }

        return $path;
    }

    public static function saveUploadedFile(UploadedFile $uploadedFile, $destinationPath, $overrideFilename = null)
    {
        $tempFilename = join(DIRECTORY_SEPARATOR, [
            $destinationPath,
            is_null($overrideFilename) ? MiscHelper::randomString(20) : basename($overrideFilename)
        ]);

        // Only add an extension if an override filename was not given, assume this is present
        if (is_null($overrideFilename))
        {
            $extension = $uploadedFile->guessExtension();
            if (!is_null($extension))
            {
                $tempFilename .= '.' . $extension;
            }
        }

        $uploadedFile->move(dirname($tempFilename), basename($tempFilename));
        return new File($tempFilename);
    }
}