package speiger.src.coreengine.utils.helpers;

import java.io.File;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;

public class IOUtils
{
	public static void ensureFolder(File file) {
		if(file.exists()) {
			if(!file.isDirectory()) {
				file.delete();
				file.mkdirs();
			}
			return;
		}
		file.mkdirs();
	}
	
	public static String convertBytes(long bytes) {
		return (bytes >> 30) > 5 ? (bytes >> 30)+"GB" : ((bytes >> 20) > 5 ? (bytes >> 20)+"MB" : ((bytes >> 10) >= 5 ? (bytes >> 10)+"KB" : bytes+"B"));
	}
	
	public static boolean endsWith(Path path, String filter) {
		return path.toString().endsWith(filter);
	}
	
	public static Path getBaseLocation() {
		try {
			return Paths.get(IOUtils.class.getProtectionDomain().getCodeSource().getLocation().toURI());
		}
		catch(Exception e) { e.printStackTrace(); }
		return Paths.get(".");
	}
	
	public static File getBase() {
		try {
			File file = new File(IOUtils.class.getProtectionDomain().getCodeSource().getLocation().toURI());
			if(file.getName().endsWith(".jar")) return file;
		}
		catch(Exception e) {}
		return new File(".");
	}
	
	public static String buildVersion(String fileName, String prefix, boolean forced_DEV, String devString) {
		if(forced_DEV) return devString;
		int index = fileName.indexOf(prefix);
		return index == -1 || fileName.length() - 4 == prefix.length() ? "Unknown Version" : fileName.substring(index + prefix.length(), fileName.length() - 4);
	}

	public static boolean isZip(Path path) {
		try(FileSystem system = FileSystems.newFileSystem(path)) { return "jar".equals(system.provider().getScheme()); }
		catch(Exception e) { return false; }
	}
}
