/**
 * 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 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.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

/**
 * 本地文件存储
 *
 * @author Chill
 */
@Slf4j
@RequiredArgsConstructor
public class LocalFileServiceImpl extends AbstractFileService {

	private final FileStorageProperties.LocalProperties properties;

	@Override
	public void uploadFile(String objectKey, InputStream inputStream) {
		Path targetPath = resolveObjectPath(objectKey);
		try {
			Files.createDirectories(targetPath.getParent());
			Files.copy(inputStream, targetPath, StandardCopyOption.REPLACE_EXISTING);
		} catch (Exception exception) {
			log.error("本地文件上传异常 objectKey：{}", objectKey, exception);
			throw new ServiceException("本地文件上传异常");
		}
	}

	@Override
	public String uploadTempFile(String objectKey, InputStream inputStream, Integer expires) {
		this.uploadFile(objectKey, inputStream);
		return this.getFileUrl(objectKey, null);
	}

	@Override
	public void uploadFile(String objectKey, File file) {
		Path targetPath = resolveObjectPath(objectKey);
		try {
			Files.createDirectories(targetPath.getParent());
			Files.copy(file.toPath(), targetPath, StandardCopyOption.REPLACE_EXISTING);
		} catch (Exception exception) {
			log.error("本地文件上传异常 objectKey：{}", objectKey, exception);
			throw new ServiceException("本地文件上传异常");
		}
	}

	@Override
	public String getFileUrl(String objectKey, String fileName, Long expires) {
		if (StringUtil.isBlank(objectKey)) {
			return null;
		}
		return properties.getAccessUrl() + "?objectKey=" + URLEncoder.encode(objectKey, StandardCharsets.UTF_8);
	}

	@Override
	public void downloadFile(String objectKey, String downloadFile) {
		Path sourcePath = resolveObjectPath(objectKey);
		try {
			Path downloadPath = Path.of(downloadFile);
			Files.createDirectories(downloadPath.getParent());
			Files.copy(sourcePath, downloadPath, StandardCopyOption.REPLACE_EXISTING);
		} catch (Exception exception) {
			log.error("本地文件下载异常 objectKey：{}", objectKey, exception);
			throw new ServiceException("本地文件下载异常");
		}
	}

	private Path resolveObjectPath(String objectKey) {
		if (StringUtil.isBlank(objectKey)) {
			throw new ServiceException("文件key不能为空");
		}
		Path rootPath = Path.of(properties.getRootPath()).toAbsolutePath().normalize();
		Path objectPath = rootPath.resolve(objectKey).normalize();
		if (!objectPath.startsWith(rootPath)) {
			throw new ServiceException("文件key不合法");
		}
		return objectPath;
	}
}
