using Minio.DataModel.Args;
using Minio;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using FileUploader.Models;

namespace Hopetry.Services
{
    class MinioService
    {

            private readonly IMinioClient _minioClient;
            private readonly string _bucketName;

            public MinioService(IConfiguration config)
            {
                var minioConfig = config.GetSection("Minio");
                _minioClient = new MinioClient()
                    .WithEndpoint(minioConfig["Endpoint"])
                    .WithCredentials(minioConfig["AccessKey"], minioConfig["SecretKey"]);

                _bucketName = minioConfig["BucketName"];
                EnsureBucketExistsAsync().Wait();
            }

            private async Task EnsureBucketExistsAsync()
            {
                var existsArgs = new BucketExistsArgs().WithBucket(_bucketName);
                if (!await _minioClient.BucketExistsAsync(existsArgs))
                {
                    var makeArgs = new MakeBucketArgs().WithBucket(_bucketName);
                    await _minioClient.MakeBucketAsync(makeArgs);
                }
            }

            public async Task UploadFileAsync(FileRecord fileRecord)
            {
                var putArgs = new PutObjectArgs()
                    .WithBucket(_bucketName)
                    .WithObject(fileRecord.FileName)
                    .WithFileName(fileRecord.LocalPath)
                    .WithContentType("application/octet-stream");
                await _minioClient.PutObjectAsync(putArgs);
            }


        
    }
}
