package com.apobates.forum.core.api;

import java.io.File;
import java.io.IOException;
import java.util.Optional;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * 缓存Topic相关的File
 * 
 * @author xiaofanku
 * @since 20191223
 */
public class TopicFileCache {
	private final String cacheDirect;
	private static TopicFileCache instance=null;
	private static String fileDirect = "topic_cache";
	private final static Logger logger = LoggerFactory.getLogger(TopicFileCache.class);
	
	private TopicFileCache(String cacheDirect) {
		super();
		this.cacheDirect = cacheDirect;
	}
	
	public static TopicFileCache getInstance(String basePath){
		if(null == instance){
			instance = new TopicFileCache(basePath + fileDirect);
		}
		return instance;
	}
	
	public File getFile(String fileName, String topicDirectName) throws IOException{
		String filePath = cacheDirect +"/"+ topicDirectName+"/"+fileName;
		File file = new File(filePath);
		if(!file.exists()){
			throw new IOException("cache file no find");
		}
		return file;
	}
	
	public File getFile(String fileName, String topicDirectName, TopicFileCacheHandler handler){
		File f = null;
		try{
			f = getFile(fileName, topicDirectName);
		}catch(IOException e){
			Optional<File> rf = handler.create();
			if(!rf.isPresent()){
				//logger.info("[TFC]"+rf.failureValue().getMessage());
				logger.info("[TFC]无可供保存的文件");
				return null;
			}
			//
			f = rf.get();
			try{
				putFile(f, fileName, topicDirectName);
			}catch(IOException e1){
				logger.info("[TFC]保存到文件时失败, 异常: "+e.getMessage());
			}
		}
		return f;
	}
	
	public void putFile(File cacheFile, String fileName, String topicDirectName) throws IOException{
		String fileDirectPath = cacheDirect +"/"+ topicDirectName +"/";
		File file = new File(fileDirectPath);
		if(!file.exists()){
			file.mkdirs();
		}
		File cf = new File(file, fileName);
		FileUtils.copyFile(cacheFile, cf);
	}
}
