<?php namespace Concore\Foundation\Providers;

use Aws\S3\S3Client;
use League\Flysystem\AwsS3v2\AwsS3Adapter;
use Google\Cloud\Storage\StorageClient;
use Illuminate\Filesystem\FilesystemManager;
use Illuminate\Support\ServiceProvider;
use League\Flysystem\Filesystem;
use Superbalist\Flysystem\GoogleStorage\GoogleStorageAdapter;

class GcsFilesystemServiceProvider extends ServiceProvider
{
    public function register()
    {

    }

    public function boot()
    {
        $factory = $this->app->make('filesystem'); /* @var FilesystemManager $factory */
        $factory->extend('gcs-keyfile', function ($app, $config) {
            $storageClient = new StorageClient([
                'projectId' => $config['project_id'],
                'keyFilePath' => array_get($config, 'key_file'),
            ]);
            $bucket = $storageClient->bucket($config['bucket']);
            $pathPrefix = array_get($config, 'path_prefix');
            $storageApiUri = array_get($config, 'storage_api_uri');
            $adapter = new GoogleStorageAdapter($storageClient, $bucket, $pathPrefix, $storageApiUri);
            return new Filesystem($adapter);
        });
        $factory->extend('gcs', function( $app, $config ) {
            $client = S3Client::factory(array(
                'key' => $config['key'],
                'secret' => $config['secret'],
                'base_url' => $config['base_url'],
            ));
            return new Filesystem(new AwsS3Adapter($client, $config['bucket']));
        });
    }
}