<?php
//https://dev.to/ediri_aghwotu/how-to-upload-files-to-google-cloud-using-laravel-3618
//https://github.com/googleapis/google-cloud-php-storage

namespace App\Modules\RemoteStorage;
use Illuminate\Support\Facades\Log;

use Google\Cloud\Storage\StorageClient;

class GoogleBucketGateway
{
    private $bucket;
    public function __construct()
    {

        $googleConfigFile = file_get_contents(base_path(config('googlestorage.key')));
        $storage = new StorageClient([
            'keyFile' => json_decode($googleConfigFile, true),
        ]);

        $this->bucket = $storage->bucket(config('googlestorage.bucket'));
    }

    public function store($source, $filename)
    {
        Log::channel('background')->info('Google bucket saved: ' . $filename); //tracing purpose   
        return $this->bucket->upload($source, [
            'predefinedAcl' => 'publicRead',
            'name' => $filename,
        ]);
    }

    public function removeFile($filename)
    {
        Log::channel('background')->info('Google bucket removed: ' . $filename); //tracing purpose   
        $object = $this->bucket->object($filename);
        try {   
            $object->delete();
            return true;
        } catch (\Exception $e) {
            if ($e->getCode() == 404) {
                return true;
            }
            return true;
        }
    }

    
}