package br.com.centralit.evm.util;

import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Util {

	private static final String PATTERN = "^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";

	// get as signed int 32 - 4 byte ---------------------- int SIGNED
	public static int getAsInt(final String value) throws NumberFormatException {
		try {
			return Integer.parseInt(value);
		} catch (final NumberFormatException e) {
			return -2202;
		}
	}

	// get as signed int 32 - 4 byte ---------------------- int SIGNED
	public static Date getAsTime(String value) throws NumberFormatException {
		if (value == null || value.isEmpty() || value.equals("")) {
			value = "0";
		}
		return new java.util.Date(Long.parseLong(value) * 1000);
	}

	// get as signed int 32 - 4 byte ---------------------- int SIGNED
	public static Timestamp getAsTimestamp(String value) throws NumberFormatException {
		if (value == null || value.isEmpty() || value.equals("")) {
			value = "0";
		}
		return new java.sql.Timestamp(Long.parseLong(value) * 1000);
	}

	// get as signed int 32 - 4 byte ---------------------- int SIGNED
	public static float getAsFloat(String value) throws NumberFormatException {
		if (value == null || value.isEmpty() || value.equals("")) {
			value = "-2202";
		}
		return Float.parseFloat(value);
	}

	public static boolean isNumeric(final String str) {
		try {
			Double.parseDouble(str);
			return true;
		} catch (final NumberFormatException nfe) {
			return false;
		}
	}

	public static boolean isValidHostAddress(final String host_address) {
		try {
			// WORKAROUND: add any scheme to make the resulting URI valid.
			final URI uri = new URI(host_address); // may throw URISyntaxException

			if (uri.getHost() == null || uri.getPort() == -1) {
				return false;
			}

			return true;
		} catch (final URISyntaxException ex) {
			return false;
		}
	}

	public static boolean validateHostAddress(final String host_address) {
		final Pattern pattern = Pattern.compile(PATTERN);
		final Matcher matcher = pattern.matcher(host_address);
		return matcher.matches();
	}

	public static boolean isLastItem(final String item, final List<String> list) {
		if (list.isEmpty()) {
			return false;
		}
		return list.get(list.size() - 1).equals(item);
	}

	public static boolean isLastItem(final String item, final String[] list) {
		if (list.length < 1) {
			return false;
		}
		return list[list.length - 1].equals(item);
	}

}