package com.zcloud.util;

import org.springframework.web.context.ServletContextAware;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * 说明：路径工具类


 */
public class PathUtil implements ServletContextAware {

	private static ServletContext servletContext;

	/**获取Projectpath
	 * @return
	 */
//	public static String getProjectpath(){
//		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//		String path = request.getSession().getServletContext().getRealPath("/").replaceAll("%20", " ").replaceAll("file:/", "").trim();

//		if (servletContext == null) {
//			throw new IllegalStateException("ServletContext is null");
//		}
//		String path = servletContext.getRealPath("/").replaceAll("%20", " ").replaceAll("file:/", "").trim();
		// 在这里使用 servletContext 对象
//		return path;
//	}

	/**获取Classpath
	 * @return
	 */
	public static String getClasspath(){
		String path =  (String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))).replaceAll("file:/", "").replaceAll("%20", " ").trim();
		if(path.indexOf(":") != 1){
			path = File.separator + path;

		}
		//path = "H:\\";  //当项目以jar、war包运行时，路径改成实际硬盘位置
		return path;
	}

	/**获取Projectpath
	 * @return
	 */
	public static String getProjectpath(){
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String path = request.getServletContext().getRealPath("/").replaceAll("%20", " ").replaceAll("file:/", "").trim();
		return path;
	}

	@Override
	public void setServletContext(ServletContext servletContext) {
		PathUtil.servletContext = servletContext;
	}
}
