package com.cmeeting.util;

import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.charset.StandardCharsets;

@Component
public class MinioUtils {
    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${minio.bucketName}")
    private String bucketName;
    @Value("${minio.accessKey}")
    private String accessKey;
    @Value("${minio.secretKey}")
    private String secretKey;

    private MinioClient minioClient;

    public synchronized MinioClient getMinioClient() {
        try {
            if(minioClient == null){
                minioClient = new MinioClient(endpoint, accessKey, secretKey);
            }
            return minioClient;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    public String getFileText(String fileName) throws IOException {
        InputStream is = getFile(fileName);
        StringBuilder textBuilder = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(is, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                textBuilder.append(line);
                textBuilder.append(System.lineSeparator());
            }
        }
        return textBuilder.toString();
    }

    public InputStream getFile(String fileName){
        try{
            getMinioClient();
            InputStream inputStream = minioClient.getObject(bucketName, fileName);
            return inputStream;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    public InputStream getFile(MinioClient minioClient, String fileName){
        try{
            InputStream inputStream = minioClient.getObject(bucketName, fileName);
            return inputStream;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
    public void upload(String path,InputStream inputStream) throws Exception{
          getMinioClient().putObject(bucketName, path, inputStream, "application/octet-stream" );
    }

    public void upload(String path,byte[] bytes) {
        try (ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes)) {
            upload(path,inputStream);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public Boolean isFileExist(MinioClient minioClient, String fileName){
        boolean found = false;
        try{
            InputStream inputStream = minioClient.getObject(bucketName, fileName);

            found= true;

            return found;

        }catch (Exception e){
            found=false;

            return  false;
        }
    }
}
