package cn.edu.seu.ise.dca.util;

public class URLUtil {
	
	/**
	 * Generate the file name that is checked out from repository
	 * We use Rev_revision_fileName to name the checked out file
	 * @param url
	 * @param revision
	 * @return
	 */
	public static String generateFileName(String url, long revision) {
		
		String[] urlSections = url.trim().split("/");
		String fileName = urlSections[urlSections.length - 1];
		return "Rev_" + revision + "_" + fileName; 
	}
	
	/**
	 * Generate the file path that is used to store in local 
	 * @param Path
	 * @param url
	 * @param revision
	 * @return
	 */
	public static String generateFilePath(String Path, String url, long revision) {
		return Path + generateFileName(url, revision);
	}
	
	/**
	 * @param url
	 * @return the directory of the file
	 */
	public static String getDir(String url) {
		int index = url.lastIndexOf("/");
		if(index < url.length()) {
			return url.substring(0, index);
		} else {
			return url;
		}
	}
	
	/**
	 * Extract the file name from the URL without suffix
	 * Make sure that URL represents file while not directory
	 * @param url
	 * @return
	 */
	public static String getFileNameWithoutSuffix(String url) {
		int index = url.lastIndexOf("/");
		String fileName = url.substring(index + 1, url.length());
		index = fileName.indexOf(".");
		if(index > -1) {
			fileName = fileName.substring(0, index);
		}
		return fileName;
	}
	
	
	/**
	 * Get the suffix of the file
	 * @param url
	 * @return
	 */
	public static String getFileSuffix(String url) {
		String suffix = "";
		int index = url.lastIndexOf("/");
		String fileName = url.substring(index + 1, url.length());
		if(fileName.contains(".")) {
			suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
		}
		return suffix;
	}
}
