/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.crunii.com</a>
 */
package com.crunii.micro.common.utils;

import java.io.File;
import java.util.List;

import org.springframework.util.ClassUtils;

import com.google.common.base.Splitter;

/**
 * @author 田平 create 2019年6月28日上午9:44:19
 */
public class LogPathUtil {

	private static final String LOG_DIR = "logs";

	public static void main(String[] args) {
		System.out.println(getNacosLogPath());
		String path = "file:/C:/Users/Administrator/Desktop/jars/micro-core-1.0.0-SNAPSHOT-exec.jar!/BOOT-INF/classes!/";
		System.out.println(getJarPath(path));
	}

	public static String getJarPath(String path) {
		StringBuilder sb = new StringBuilder();
		List<String> strs = Splitter.on("/").splitToList(path);
		for (int i = 0; i < strs.size(); i++) {
			String str = strs.get(i);
			if (i == 0) {
				continue;
			} else if (strs.get(i).indexOf("exec.jar!") > -1) {
				break;
			} else {
				sb.append(str).append("/");
			}
		}
		return sb.toString();
	}

	public static String getNacosLogPath() {
		String nacosLogPath = ClassUtils.getDefaultClassLoader().getResource("").getPath();
		String path = "";
		if (nacosLogPath.startsWith("file:")) {
			path = getJarPath(nacosLogPath) + LOG_DIR;
		} else {
			int idx = nacosLogPath.lastIndexOf("target");
			String os = System.getProperty("os.name").toLowerCase();
			if (os.indexOf("windows") > -1) {
				path = nacosLogPath.substring(1, idx) + LOG_DIR;
			} else {
				path = nacosLogPath.substring(0, idx) + LOG_DIR;
			}
		}
		File file = new File(path);
		if (!file.exists()) {
			file.mkdir();
		}
		return path;
	}
}
