import io.minio.MinioClient;
import io.minio.errors.MinioException;
import io.minio.messages.Bucket;
import java.util.List;
import java.util.regex.Pattern;

public class BucketManager {
    MinioClient minioClient;

    public BucketManager(String minioAddress, String minioAdmin, String minioPassword) {
        minioClient = MinioClient.builder()
            .endpoint(minioAddress)
            .credentials(minioAdmin, minioPassword)
            .build();
    }

    public void createBucket(String bucketName) {
        try {
            boolean isExist = minioClient.bucketExists(bucketName);
            if (isExist) {
                System.out.println("该存储桶已经存在");
            } else {
                minioClient.makeBucket(bucketName);
                System.out.println("存储桶创建成功");
            }
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
        }
    }

    public List<Bucket> listBuckets() throws MinioException {
        return minioClient.listBuckets();
    }

    public void removeBucket(String bucketName) {
        try {
            minioClient.removeBucket(bucketName);
            System.out.println("删除存储桶 " + bucketName + " 成功");
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
        }
    }

    public void uploadFile(String bucketName, String objectName, String filePath) {
        try {
            boolean isExist = minioClient.bucketExists(bucketName);
            if (!isExist) {
                minioClient.makeBucket(bucketName);
            }
            minioClient.uploadObject(
                bucketName, objectName, filePath);
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
        }
    }

    public void downloadFile(String bucketName, String objectName, String filePath) {
        try {
            minioClient.downloadObject(bucketName, objectName, filePath);
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
        }
    }

    public void removeObject(String bucketName, String objectName) {
        try {
            minioClient.removeObject(bucketName, objectName);
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
        }
    }

    public boolean pathValidation(String objectName) {
        String pattern = "^a\\/(b|c)\\/[^\\/]+\\/[^\\/]+\\/[^\\/]+\\/[^\\/]+\\/[^\\/]+$";
        return Pattern.matches(pattern, objectName);
    }
}