using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using GxPress.Common.Exceptions;
using Minio;

namespace GxPress.Common.Tools
{
    /// <summary>
    /// 迷你IQ读写
    /// </summary>
    public class MinIOHelper
    {
        private const string EndPoint = "192.168.0.112:9000";
        private const string AccessKey = "5RLR47A3A8RV72VPBNLQ";
        private const string SecretKey = "FEss1GPMP7ifDPENRFflntSUpQcMB59wpTDwfa4F";
        private const string Location = "us-east-1";
        private static MinioClient _io;

        public MinIOHelper()
        {
            if (_io == null)
            {
                _io = new MinioClient(EndPoint, AccessKey, SecretKey);
            }
        }

        /// <summary>
        /// 创建存储文件
        /// </summary>
        /// <param name="bucketName"></param>
        /// <returns></returns>
        public async Task<bool> MakeBucketAsync(string bucketName)
        {
            var found = await _io.BucketExistsAsync(bucketName);
            if (!found)
            {
                await _io.MakeBucketAsync(bucketName, Location);
            }

            return true;
        }

        /// <summary>
        /// 路径添加
        /// </summary>
        /// <param name="bucketName">库名</param>
        /// <param name="objectName">后缀名称</param>
        /// <param name="filePath">地址</param>
        /// <param name="contentType">类型</param>
        /// <returns></returns>
        public async Task<bool> PutObjectAsync(string bucketName, string objectName, string filePath,
            string contentType)
        {
            try
            {
                if (await MakeBucketAsync(bucketName))
                {
                    await _io.PutObjectAsync(bucketName, objectName, filePath, contentType);
                }
            }
            catch (Exception e)
            {
                throw new BusinessException(e.Message);
            }

            return true;
        }

        /// <summary>
        /// 文件流添加
        /// </summary>
        /// <param name="bucketName">库名</param>
        /// <param name="objectName">后缀名称</param>
        /// <param name="data">文件流</param>
        /// <returns></returns>
        public async Task<bool> PutByteObjectAsync(string bucketName, string objectName, Stream data)
        {
            try
            {
                await MakeBucketAsync(bucketName);
                await _io.PutObjectAsync(bucketName, objectName, data, data.Length, "application/octet-stream");
            }
            catch (Exception e)
            {
                throw new BusinessException(e.Message);
            }

            return true;

        }
    }
}
