package com.reallinkbilling.db;

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

public class GetDBConnection {

	

	private static final ConnectionTarget LOCAL_SPENCA = new ConnectionTarget(
			"local-reallinkshop",
			"jdbc:mysql://localhost:3306/spencainvent?useSSL=false&useUnicode=true&characterEncoding=UTF-8",
			"root",
			"rahullondhe");

	private static final ConnectionTarget REMOTE_SEPNCA = new ConnectionTarget(
			"remote-easysbill",
			"jdbc:mysql://103.211.202.254:3306/spencawater_original?useSSL=false&useUnicode=true&characterEncoding=UTF-8",
			"spencawater_admin",
			"sreDdl&%C)loUmPP");

	private static final ConnectionTarget LOCAL_SEPNCA_ORIGINAL = new ConnectionTarget(
			"local-easysbill-original",
			"jdbc:mysql://localhost:3306/spencawater_original?useSSL=false&useUnicode=true&characterEncoding=UTF-8",
			"spencawater_admin",
			"sreDdl&%C)loUmPP");

	/**
	 * Activate exactly one connection, then restart Tomcat.
	 */
	// private static final ConnectionTarget ACTIVE_CONNECTION = LOCAL_SPENCA;
	//private static final ConnectionTarget ACTIVE_CONNECTION = REMOTE_SEPNCA;
	private static final ConnectionTarget ACTIVE_CONNECTION = LOCAL_SEPNCA_ORIGINAL;

	private static final int MAXIMUM_POOL_SIZE = 30;
	private static final int MINIMUM_IDLE = 0;
	private static final long CONNECTION_TIMEOUT_MS = 30000;
	private static final long IDLE_TIMEOUT_MS = 60000;
	private static final long MAX_LIFETIME_MS = 240000;
	private static final long KEEPALIVE_TIME_MS = 30000;
	private static final long LEAK_DETECTION_MS = 20000;
	private static final long MAX_BORROW_MS = 120000;

	private static final ConcurrentHashMap<String, HikariDataSource> POOLS = new ConcurrentHashMap<String, HikariDataSource>();
	private static final ConcurrentHashMap<Connection, Borrow> CHECKED_OUT = new ConcurrentHashMap<Connection, Borrow>();
	private static volatile boolean reaperRunning = true;

	static {
		Thread reaper = new Thread(new Runnable() {
			public void run() {
				while (reaperRunning) {
					try {
						Thread.sleep(15000);
					} catch (InterruptedException e) {
						break;
					}
					long now = System.currentTimeMillis();
					for (Map.Entry<Connection, Borrow> entry : new ArrayList<Map.Entry<Connection, Borrow>>(CHECKED_OUT.entrySet())) {
						Borrow borrow = entry.getValue();
						if (borrow != null && now - borrow.at > MAX_BORROW_MS) {
							System.err.println("Returning abandoned database connection checked out for "
									+ ((now - borrow.at) / 1000) + " seconds");
							borrow.stack.printStackTrace();
							release(entry.getKey());
						}
					}
				}
			}
		}, "easysbill-connection-reaper");
		reaper.setDaemon(true);
		reaper.start();
	}

	public static Connection getDBConnection(String schema) throws SQLException, IOException {

		if (schema == null) {
			return null;
		}

		try {
			HikariDataSource dataSource = getOrCreatePool(schema);
			if (dataSource == null) {
				return null;
			}
			return track(dataSource.getConnection());
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return null;
	}

	public static void shutdown() {
		reaperRunning = false;
		for (Connection connection : new ArrayList<Connection>(CHECKED_OUT.keySet())) {
			release(connection);
		}
		for (HikariDataSource dataSource : POOLS.values()) {
			if (dataSource != null && !dataSource.isClosed()) {
				dataSource.close();
			}
		}
		POOLS.clear();
	}

	private static HikariDataSource getOrCreatePool(String schema) {
		HikariDataSource dataSource = POOLS.get(schema);
		if (dataSource != null) {
			return dataSource;
		}

		synchronized (GetDBConnection.class) {
			dataSource = POOLS.get(schema);
			if (dataSource == null) {
				dataSource = createPool(schema);
				if (dataSource != null) {
					POOLS.put(schema, dataSource);
				}
			}
		}
		return dataSource;
	}

	private static HikariDataSource createPool(String schema) {
		if (!schema.equals("reallinkshop")) {
			return null;
		}

		HikariConfig config = new HikariConfig();
		config.setPoolName("easysbill-" + ACTIVE_CONNECTION.name);
		config.setDriverClassName("com.mysql.jdbc.Driver");
		config.setJdbcUrl(ACTIVE_CONNECTION.jdbcUrl);
		config.setUsername(ACTIVE_CONNECTION.username);
		config.setPassword(ACTIVE_CONNECTION.password);
		config.setMaximumPoolSize(MAXIMUM_POOL_SIZE);
		config.setMinimumIdle(MINIMUM_IDLE);
		config.setConnectionTimeout(CONNECTION_TIMEOUT_MS);
		config.setIdleTimeout(IDLE_TIMEOUT_MS);
		config.setMaxLifetime(MAX_LIFETIME_MS);
		config.setAutoCommit(true);
		config.setKeepaliveTime(KEEPALIVE_TIME_MS);
		config.setLeakDetectionThreshold(LEAK_DETECTION_MS);
		config.setConnectionTestQuery("SELECT 1");

		return new HikariDataSource(config);
	}

	private static Connection track(final Connection connection) {
		CHECKED_OUT.put(connection, new Borrow());
		return (Connection) Proxy.newProxyInstance(GetDBConnection.class.getClassLoader(), new Class[] { Connection.class },
				new InvocationHandler() {
					public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
						if ("close".equals(method.getName())) {
							release(connection);
							return null;
						}
						try {
							return method.invoke(connection, args);
						} catch (InvocationTargetException ex) {
							throw ex.getCause();
						}
					}
				});
	}

	private static void release(Connection connection) {
		if (CHECKED_OUT.remove(connection) != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	private static final class Borrow {
		private final long at = System.currentTimeMillis();
		private final Exception stack = new Exception("Connection borrowed here and not closed");
	}

	private static final class ConnectionTarget {
		private final String name;
		private final String jdbcUrl;
		private final String username;
		private final String password;

		private ConnectionTarget(String name, String jdbcUrl, String username, String password) {
			this.name = name;
			this.jdbcUrl = jdbcUrl;
			this.username = username;
			this.password = password;
		}
	}
}
