<?php

// load admin related code
$this->on('app.admin.init', function() {

    $this->helper('license')->require();

});

// events
$this->on('app.filestorage.init', function(&$storages) {

    $config = $this->retrieve('cloudStorage');

    if (!$config) {
        return;
    }

    foreach ($config as $key => $settings) {

        if (!$settings) {
            continue;
        }

        $type = $settings['type'] ?? 's3';
        $settings['prefix'] = $settings['prefix'] ?? '';

        switch ($type) {

            case 'azure':

                // run composer require azure-oss/storage-blob-flysystem
                if (!class_exists('AzureOss\Storage\Blob\BlobServiceClient')) {
                    throw new Exception('Azure Blob filestorage adapter is not installed. Run `composer require azure-oss/storage-blob-flysystem` to install it.');
                }

                if (!isset($settings['container'])) {
                    throw new Exception('Azure Blob container is not defined.');
                }

                if (isset($settings['key'], $settings['account'])) {
                    $settings['connectionString'] = sprintf('DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s;EndpointSuffix=core.windows.net', $settings['account'], $settings['key']);
                }

                if (!isset($settings['connectionString'])) {
                    throw new Exception('Azure Blob connection string is not defined.');
                }

                $url = $settings['url'] ?? "https://{$settings['account']}.blob.core.windows.net/{$settings['container']}";

                if (!isset($settings['url']) && $settings['prefix']) {
                    $url .= "/{$settings['prefix']}";
                }

                $blobServiceClient = AzureOss\Storage\Blob\BlobServiceClient::fromConnectionString($settings['connectionString']);
                $containerClient = $blobServiceClient->getContainerClient($settings['container']);

                $storages[$key] = [
                    'adapter' => 'AzureOss\FlysystemAzureBlobStorage\AzureBlobStorageAdapter',
                    'args'    => [$containerClient, $settings['prefix']],
                    'mount'   => true,
                    'url'     => $url
                ];

                break;

            case 's3':

                if (!isset($settings['key'])) throw new Exception('AWS S3 key is not defined.');
                if (!isset($settings['secret'])) throw new Exception('AWS S3 secret is not defined.');
                if (!isset($settings['bucket'])) throw new Exception('AWS S3 bucket is not defined.');
                if (!isset($settings['region']))  throw new Exception('AWS S3 region is not defined.');

                $url = $settings['url'] ?? "https://s3.{$settings['region']}.amazonaws.com/{$settings['bucket']}";

                if (!isset($settings['url']) && $settings['prefix']) {
                    $url .= "/{$settings['prefix']}";
                }

                $client = new Aws\S3\S3Client(array_merge([
                        'credentials' => [
                            'key'    => $settings['key'],
                            'secret' => $settings['secret']
                        ],
                        'region'  => $settings['region'],
                        'version' => $settings['version'] ?? 'latest',
                ], isset($settings['endpoint']) ? [
                    'endpoint' => $settings['endpoint']
                ] : []));

                $storages[$key] = [
                    'adapter' => 'League\Flysystem\AwsS3V3\AwsS3V3Adapter',
                    'args'    => [$client, $settings['bucket'], $settings['prefix']],
                    'mount'   => true,
                    'url'     => $url,
                    'visibility' => $settings['visibility'] ?? 'public',
                ];

                break;
        }

    }
});

$this->on('assets.asset.remove', function($asset) {

    // remove cached asset if cloudstorage is used
    if ($cached = $this->path("#uploads:{$asset['path']}")) {
        unlink($cached);
    }
});
