package up6.biz;

import java.io.File;
import java.io.IOException;

import org.apache.commons.lang.StringUtils;

import net.sf.json.JSONObject;
import up6.ConfigReader;
import up6.PathTool;
import up6.model.FileInf;


public class PathBuilder {
	
	public PathBuilder(){}
	
	/**
	 * 获取上传路径
	 * 格式：
	 * 	webapp_name/upload
	 * @return
	 * @throws IOException
	 */
	public String getRoot() throws IOException{

		String root = new String("");
		//前面会多返回一个"/", 例如  /D:/test/WEB-INF/, 奇怪, 所以用 substring()
		root = this.getClass().getResource("/").getPath().substring(1).replaceAll("//", "/");
		if ( !StringUtils.isBlank(root) && !root.endsWith("/"))
		{
			root = root.concat("/");    //避免 WebLogic 和 WebSphere 不一致
		}
		root = root.replace("classes/", "");
		//D:/apache-tomcat-6.0.29/webapps/Uploader6.1MySQL/WEB-INF/
		root = root.replace("%20", " ");//fix(2016-02-29):如果路径中包含空格,getPath会自动转换成%20
		//D:/apache-tomcat-6.0.29/webapps/Uploader6.1MySQL
		root = root.replace("WEB-INF/", "");
		//D:/apache-tomcat-6.0.29/webapps/Uploader6.1MySQL/upload
		//root = root.concat("upload/");	
		

		ConfigReader cr = new ConfigReader();
		JSONObject jo =  cr.module("path");
		String pathSvr = jo.getString("upload-folder");
		pathSvr = pathSvr.replace("{root}", root);
		pathSvr = pathSvr.replaceAll("\\\\", "/");
		return pathSvr;
	}
	public String genFolder(FileInf fd) throws IOException{return "";}
	public String genFile(int uid,FileInf f) throws IOException{return "";}
	public String genFile(int uid,String md5,String nameLoc)throws IOException{return "";}
	/**
	 * 相对路径转换成绝对路径
	 * 格式：
	 * 	/2021/05/28/guid/nameLoc => d:/upload/2021/05/28/guid/nameLoc
	 * @return
	 * @throws IOException
	 */
	public String relToAbs(String path) throws IOException
	{
		String root = this.getRoot();
		root = root.replaceAll("\\\\", "/");
		path = path.replaceAll("\\\\", "/");
		if(path.startsWith("/"))
		{
			path = PathTool.combine(root, path);
		}
		return path;
	}
	/**
	 * 将路径转换成相对路径
	 * @return
	 * @throws IOException
	 */
	public String absToRel(String path) throws IOException
	{
		String root = this.getRoot().replaceAll("\\\\", "/");
		path = path.replaceAll("\\\\", "/");
		path = path.replaceAll(root, "");
		return path;
	}
}
