package com.ads.business.service.impl;

import com.ads.business.service.FileService;
import com.ads.common.data.GetPictureConfigInData;
import com.ads.common.data.GetPicturePathOutData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

@Service
public class FileServiceImpl implements FileService {

	@Autowired
	private GetPictureConfigInData pictureConfig;

	@Override
	public GetPicturePathOutData createUploadPath(String pictureName) {
		// 上传文件的保存路径
		Path storePath = Paths.get(pictureConfig.getBasePath(), pictureConfig.getUploadPath(), pictureName);
		// 上传文件的显示路径
		String serverPath = new StringBuilder(pictureConfig.getServerBasePath()).append("/").append(pictureConfig.getUploadPath()).append("/")
		        .append(pictureName).toString();
		return new GetPicturePathOutData(serverPath, storePath);
	}

	@Override
	public void savePicture(byte[] bytes, GetPicturePathOutData picturePath) throws Exception {
		Path storePath = picturePath.getStoragePath();
		Path parentPath = storePath.getParent();
		if (!Files.exists(parentPath)) {
			Files.createDirectories(parentPath);
		}
		Files.write(storePath, bytes, StandardOpenOption.CREATE);
	}

}
