package speiger.src.coreengine.utils.helpers;

import java.text.DecimalFormat;
import java.util.Locale;

import speiger.src.coreengine.math.misc.ColorObject;
import speiger.src.coreengine.utils.io.GameLog;
import speiger.src.coreengine.utils.io.GameLog.LogLevel;

public class TextUtil
{
	public static String removeSpecialFormatters(String input)
	{
		return input.replaceAll("\\§\\<(.*?)\\>", "");
	}
	
	public static String makeColor(Integer color)
	{
		return "§<color"+(color == null ? "" : "="+color.intValue())+">";
	}
	
	public static ColorObject getColorFromText(String s)
	{
		s = s == null ? "" : s;
		return ColorObject.rgb((s.hashCode() & 11184810) + 4473924);
	}
	
	public static String searchUntil(String s, int startIndex, char endChar, String invalidChars)
	{
		boolean found = false;
		invalidChars = invalidChars.toLowerCase(Locale.ROOT);
		StringBuilder builder = new StringBuilder();
		while(startIndex < s.length())
		{
			char character = s.charAt(startIndex);
			if(character == endChar)
			{
				found = true;
				break;
			}
			if(invalidChars.contains(Character.toString(character).toLowerCase(Locale.ROOT)))
			{
				break;
			}
			builder.append(character);
			startIndex++;
		}
		if(!found)
		{
			return "";
		}
		return builder.toString();
	}
	
	public static boolean findFlag(String value, String search, boolean original)
	{
		if(value.startsWith(search))
		{
			int equals = value.indexOf("=");
			return equals == -1 ? !original : (Boolean.parseBoolean(value.substring(equals + 1)));
		}
		return original;
	}
	
	public static ColorObject findColor(String value, String search, ColorObject current, ColorObject original)
	{
		if(value.startsWith(search))
		{
			try
			{
				int equals = value.indexOf("=");
				return equals == -1 ? original : ColorObject.rgb(Integer.decode(value.substring(equals + 1)).intValue());
			}
			catch(Exception e)
			{
				GameLog.error("Color Parsing failed", e, LogLevel.WARNING);
			}
		}
		return current;
	}
	
	public static float findFloat(String value, String search, float current, float toggleValue)
	{
		if(value.startsWith(search))
		{
			int equals = value.indexOf("=");
			return equals == -1 ? toggleValue : (Float.parseFloat(value.substring(equals + 1)));
		}
		return current;
	}
	
	public static String convertTime(long time, String key, DecimalFormat format)
	{
		return key + (time >= 1000000 ? format.format(time /= 1000000)+"ms" : (time >= 1000 ? format.format(time /= 1000)+"qs" : format.format(time)+"ns"));
	}
	
	public static String repeate(String s, int amount)
	{
		StringBuilder builder = new StringBuilder();
		for(int i = 0;i<amount;i++)
		{
			builder.append(s);
		}
		return builder.toString();
	}
}
