package com.rjconsultores.ventaboletos.web.utilerias;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


public class IPValidatorUtileria {

	private static Logger log = LogManager.getLogger(IPValidatorUtileria.class);

	private Pattern pattern;
	private Matcher matcher;

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

	public IPValidatorUtileria() {
		pattern = Pattern.compile(IPADDRESS_PATTERN);
	}

	/**
	 * Validate ip address with regular expression
	 * 
	 * @param ip
	 *            ip address for validation
	 * @return true valid ip address, false invalid ip address
	 */
	public boolean validate(final String ip) {
		matcher = pattern.matcher(ip);
		return matcher.matches();
	}

	public static String getIp() {
		try {
			return InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
			log.error("", e);
		}
		return null;
	}

	public static String getIpExternalAWS() {
		BufferedReader in = null;
		try {
			URL whatismyip = new URL("http://checkip.amazonaws.com");
			in = new BufferedReader(new InputStreamReader(whatismyip.openStream()));
			String ip = in.readLine();
			return ip;
		} catch (MalformedURLException e1) {
			log.error("", e1);
		} catch (IOException e) {
			log.error("", e);
		} finally {
			if (in != null) {
				try {
					in.close();

				} catch (IOException e) {
					log.error("", e);
				}
			}
		}
		return null;
	}

	public static void main(String[] args) {
		System.out.println("Current IP address : " + IPValidatorUtileria.getIp());
		System.out.println("Current IP address AWS: " + IPValidatorUtileria.getIpExternalAWS());
	}
}
