<?php

namespace App\Helpers;

use Illuminate\Http\UploadedFile;
use Symfony\Component\HttpFoundation\File\File;

class FileHelper
{
    public static function deleteIfEmpty($folderPath)
    {
        // Another request may have got here first!
        if (!is_dir($folderPath))
        {
            return;
        }

        $queueIterator = new \DirectoryIterator($folderPath);
        $files = 0;

        foreach ($queueIterator as $item)
        {
            if ($item->isDot())
            {
                continue;
            }

            $files++;
        }

        if ($files == 0)
        {
            @rmdir($folderPath);
        }
    }

    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 saveExtractedFile(File $extractedFile, $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 = $extractedFile->guessExtension();
            if (!is_null($extension))
            {
                $tempFilename .= '.' . $extension;
            }
        }

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

    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);
    }
}