package de.siphalor.was.util;

import java.io.IOException;
import java.util.function.IntPredicate;
import java.util.function.Predicate;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

/**
 * A utility collection.
 */
public class Util {
	/**
	 * The main logger
	 */
	public static final Logger LOGGER;

	/**
	 * A predicate that always returns <code>true</code>
	 */
	private static final Predicate<?> DUMMY_PREDICATE = o -> true;
	/**
	 * An int predicate that always returns <code>true</code>
	 */
	private static final IntPredicate DUMMY_INT_PREDICATE = value -> true;

	/**
	 * An empty array
	 */
	private static final Object[] EMPTY_ARRAY = new Object[0];

	/**
	 * Gets an always true predicate.
	 * @param <T> The type of the predicate
	 * @return A predicate that always returns <code>true</code>
	 */
	@SuppressWarnings("unchecked")
	public static <T> Predicate<T> dummyPredicate() {
		return (Predicate<T>) DUMMY_PREDICATE;
	}

	/**
	 * Gets an always true int predicate.
	 * @return An int predicate that always returns <code>true</code>
	 */
	public static IntPredicate dummyIntPredicate() {
		return DUMMY_INT_PREDICATE;
	}

	/**
	 * Gets an empty array of the given type. No memory allocations for this stuff. Also convenient
	 * @param <T> The array type
	 * @return The empty array
	 */
	@SuppressWarnings("unchecked")
	public static <T> T[] emptyArray() {
		return (T[]) EMPTY_ARRAY;
	}

	/**
	 * Converts a relative path to a resource id.
	 * @param packId The pack where the resource lives
	 * @param path The relative path to the resource
	 * @return The resource id
	 */
	public static String pathToId(String packId, String path) {
		int dot = path.lastIndexOf('.');
		if (dot >= 0) {
			path = path.substring(0, dot);
		}
		path = path.replace('/', '.').replace('\\', '.');
		if (packId.isEmpty()) {
			return path;
		}
		return packId + "." + path;
	}

	static {
		LOGGER = Logger.getLogger("");
		try {
			FileHandler logFile = new FileHandler("was.log");
			logFile.setLevel(Level.FINEST);
			logFile.setFormatter(new SimpleFormatter());
			LOGGER.addHandler(logFile);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
