/**
 * BladeX Commercial License Agreement
 * Copyright (c) 2018-2099, https://bladex.cn. All rights reserved.
 * <p>
 * Use of this software is governed by the Commercial License Agreement
 * obtained after purchasing a license from BladeX.
 * <p>
 * 1. This software is for development use only under a valid license
 * from BladeX.
 * <p>
 * 2. Redistribution of this software's source code to any third party
 * without a commercial license is strictly prohibited.
 * <p>
 * 3. Licensees may copyright their own code but cannot use segments
 * from this software for such purposes. Copyright of this software
 * remains with BladeX.
 * <p>
 * Using this software signifies agreement to this License, and the software
 * must not be used for illegal purposes.
 * <p>
 * THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY. The author is
 * not liable for any claims arising from secondary or illegal development.
 * <p>
 * Author: Chill Zhuang (bladejava@qq.com)
 */
package org.springblade.file.service.impl;

import io.minio.GetObjectArgs;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.UploadObjectArgs;
import io.minio.http.Method;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.file.config.FileStorageProperties;

import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.time.Duration;
import java.util.Optional;

/**
 * MinIO文件存储
 *
 * @author Chill
 */
@Slf4j
@RequiredArgsConstructor
public class MinioFileServiceImpl extends AbstractFileService {

	private static final long PART_SIZE = 10 * 1024 * 1024L;

	private final FileStorageProperties.StoreProperties properties;
	private final MinioClient minioClient;

	@Override
	public void uploadFile(String objectKey, InputStream inputStream) {
		try {
			minioClient.putObject(PutObjectArgs.builder()
				.bucket(properties.getBucketName())
				.object(resolveObjectKey(objectKey))
				.stream(inputStream, -1, PART_SIZE)
				.build());
		} catch (Exception exception) {
			log.error("MinIO文件上传异常 objectKey：{}", objectKey, exception);
			throw new ServiceException("MinIO文件上传异常");
		}
	}

	@Override
	public String uploadTempFile(String objectKey, InputStream inputStream, Integer expires) {
		this.uploadFile(objectKey, inputStream);
		return this.getFileUrl(objectKey, Optional.ofNullable(expires).map(Duration::ofDays).map(Duration::toSeconds).orElse(null));
	}

	@Override
	public void uploadFile(String objectKey, File file) {
		try {
			minioClient.uploadObject(UploadObjectArgs.builder()
				.bucket(properties.getBucketName())
				.object(resolveObjectKey(objectKey))
				.filename(file.getAbsolutePath())
				.build());
		} catch (Exception exception) {
			log.error("MinIO文件上传异常 objectKey：{}", objectKey, exception);
			throw new ServiceException("MinIO文件上传异常");
		}
	}

	@Override
	public String getFileUrl(String objectKey, String fileName, Long expires) {
		if (StringUtil.isBlank(objectKey)) {
			return null;
		}
		try {
			return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
				.method(Method.GET)
				.bucket(properties.getBucketName())
				.object(resolveObjectKey(objectKey))
				.expiry(Math.toIntExact(resolveExpires(expires)))
				.build());
		} catch (Exception exception) {
			log.error("MinIO获取文件链接异常 objectKey：{}", objectKey, exception);
			throw new ServiceException("MinIO获取文件链接异常");
		}
	}

	@Override
	public void downloadFile(String objectKey, String downloadFile) {
		try (InputStream inputStream = minioClient.getObject(GetObjectArgs.builder()
			.bucket(properties.getBucketName())
			.object(resolveObjectKey(objectKey))
			.build())) {
			Path downloadPath = Path.of(downloadFile);
			Files.createDirectories(downloadPath.getParent());
			Files.copy(inputStream, downloadPath, StandardCopyOption.REPLACE_EXISTING);
		} catch (Exception exception) {
			log.error("MinIO文件下载异常 objectKey：{}", objectKey, exception);
			throw new ServiceException("MinIO文件下载异常");
		}
	}

	private String resolveObjectKey(String objectKey) {
		if (StringUtil.isBlank(properties.getRootDirectory())) {
			return objectKey;
		}
		if (properties.getRootDirectory().endsWith("/")) {
			return properties.getRootDirectory() + objectKey;
		}
		return properties.getRootDirectory() + "/" + objectKey;
	}

	private Long resolveExpires(Long expires) {
		return Optional.ofNullable(expires)
			.orElse(Optional.ofNullable(properties.getExpires()).orElse(Duration.ofHours(1).toSeconds()));
	}
}
