/**
 * 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 com.aliyun.oss.OSS;
import com.aliyun.oss.model.GetObjectRequest;
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.time.Duration;
import java.util.Date;
import java.util.Optional;

/**
 * 阿里云OSS文件存储
 *
 * @author Chill
 */
@Slf4j
@RequiredArgsConstructor
public class OssFileServiceImpl extends AbstractFileService {

	private final FileStorageProperties.StoreProperties properties;
	private final OSS ossClient;

	@Override
	public void uploadFile(String objectKey, InputStream inputStream) {
		try {
			ossClient.putObject(properties.getBucketName(), resolveObjectKey(objectKey), inputStream);
		} catch (Exception exception) {
			log.error("OSS文件上传异常 objectKey：{}", objectKey, exception);
			throw new ServiceException("OSS文件上传异常");
		}
	}

	@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 {
			ossClient.putObject(properties.getBucketName(), resolveObjectKey(objectKey), file);
		} catch (Exception exception) {
			log.error("OSS文件上传异常 objectKey：{}", objectKey, exception);
			throw new ServiceException("OSS文件上传异常");
		}
	}

	@Override
	public String getFileUrl(String objectKey, String fileName, Long expires) {
		if (StringUtil.isBlank(objectKey)) {
			return null;
		}
		try {
			Date expiration = new Date(System.currentTimeMillis() + resolveExpires(expires) * 1000);
			return ossClient.generatePresignedUrl(properties.getBucketName(), resolveObjectKey(objectKey), expiration).toString();
		} catch (Exception exception) {
			log.error("OSS获取文件链接异常 objectKey：{}", objectKey, exception);
			throw new ServiceException("OSS获取文件链接异常");
		}
	}

	@Override
	public void downloadFile(String objectKey, String downloadFile) {
		try {
			ossClient.getObject(new GetObjectRequest(properties.getBucketName(), resolveObjectKey(objectKey)), new File(downloadFile));
		} catch (Exception exception) {
			log.error("OSS文件下载异常 objectKey：{}", objectKey, exception);
			throw new ServiceException("OSS文件下载异常");
		}
	}

	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()));
	}
}
