<?php

namespace App\Helpers\FirstParty\OSSUploader;

use Exception;
use Illuminate\Support\Facades\Storage;

class OSSUploader
{
    public static function readJson($storage_driver, $relative_directory, $filename)
    {
        $filepath = rtrim($relative_directory, '/').'/'.$filename;

        try {
            $jsonContent = Storage::disk($storage_driver)->get($filepath);

            $decodedJson = json_decode($jsonContent, false, 512);

            return $decodedJson;

        } catch (\Exception $e) {
            return null;
        }

        return null;
    }

    public static function readFile($storage_driver, $relative_directory, $filename)
    {
        $filepath = rtrim($relative_directory, '/').'/'.$filename;

        try {
            return Storage::disk($storage_driver)->get($filepath);

        } catch (\Exception $e) {
            return null;
        }

        return null;
    }

    public static function uploadJson($storage_driver, $relative_directory, $filename, $jsonData)
    {
        $jsonString = json_encode($jsonData, JSON_PRETTY_PRINT);

        try {
            return self::uploadFile($storage_driver, $relative_directory, $filename, $jsonString);
        } catch (Exception $e) {
            return false;
        }

        return false;

    }

    public static function uploadFile($storage_driver, $relative_directory, $filename, $file)
    {
        $filepath = rtrim($relative_directory, '/').'/'.$filename;

        // if(!Storage::disk($storage_driver)->exists($relative_directory))
        // {
        //     Storage::disk($storage_driver)->makeDirectory($relative_directory);
        // }

        return Storage::disk($storage_driver)->put($filepath, $file);
    }
}
