package in.gov.digilocker.uidai.services.resources;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PostData {
	private static final String UNICODE = "utf-8";
	private static final Logger logger = LoggerFactory.getLogger(PostData.class);

	public String excutePostXml(String targetURL, String urlParameters, String contentType) throws Exception {
		try {
				String data = "";
				if (targetURL.matches("^(https)://.*$")) {
					URL url;
					HttpsURLConnection connection = null;
					SSLContext sslcontext = null;
					sslcontext = SSLContext.getInstance("SSL");
					sslcontext.init(new KeyManager[0], new TrustManager[] { new MyTrustManager() }, new SecureRandom());
					SSLSocketFactory factory = sslcontext.getSocketFactory();
					url = new URL(targetURL);
					connection = (HttpsURLConnection) url.openConnection();
					connection.setRequestMethod("POST");
					
					connection.setConnectTimeout(30 * 1000); 
					connection.setReadTimeout(30 *1000);

					
					connection.setRequestProperty("Accept-Charset", UNICODE);
					connection.setRequestProperty("Content-Type", contentType+"charset=" + UNICODE);
					connection.setRequestProperty("User-Agent", "Mozilla/5.0");
					connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes(UNICODE).length));
					connection.setRequestProperty("Content-Language", "en-US");
					connection.setUseCaches(false);
					connection.setDoInput(true);
					connection.setDoOutput(true);
					connection.setSSLSocketFactory(factory);
					connection.setHostnameVerifier(new MyHostNameVerifier());
					/* Send request */
					try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
						BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(wr, UNICODE));
						writer.write(urlParameters);
						writer.close();
						wr.flush();
						wr.close();
					}
					
					int responseCode = connection.getResponseCode();
					logger.info("Response code is:----" +responseCode);
					
					if (responseCode != 200) {
						throw new RuntimeException("Connection time out.");
					}
					
					String encoding = connection.getContentEncoding() == null ? UNICODE : connection.getContentEncoding();
					try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding))) {
						String line = "";
						StringWriter writer = new StringWriter();
						while ((line = in.readLine()) != null) {
							writer.write(line);
						}
						in.close();
						writer.close();
						data = writer.toString();
					}
					return data;

				} else {
					URL url;
					HttpURLConnection connection = null;
					url = new URL(targetURL);
					connection = (HttpURLConnection) url.openConnection();
					connection.setRequestMethod("POST");
					connection.setRequestProperty("User-Agent", "Mozilla/5.0");
					connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes(UNICODE).length));
					connection.setRequestProperty("Accept-Charset", UNICODE);
					connection.setRequestProperty("Content-Type", contentType+"charset=" + UNICODE);
					connection.setConnectTimeout(30 * 1000); 
					connection.setReadTimeout(30 *1000);
					connection.setUseCaches(false);
					connection.setDoInput(true);
					connection.setDoOutput(true);
					try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
						BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(wr, UNICODE));
						writer.write(urlParameters);
						writer.close();
						wr.flush();
						wr.close();
					}
					int responseCode = connection.getResponseCode();
					logger.info("Response code is:----" +responseCode);
					if (responseCode != 200) {
						throw new RuntimeException("Connection time out.");
					}
					try (BufferedReader in = new BufferedReader(
							new InputStreamReader(connection.getInputStream(), UNICODE))) {
						String line = "";
						StringWriter writer = new StringWriter();
						while ((line = in.readLine()) != null) {
							writer.write(line);
						}
						data = writer.toString();
						in.close();
						writer.close();
					}
					return data;

				}
			
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	private static class MyTrustManager implements X509TrustManager {
		public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		public X509Certificate[] getAcceptedIssuers() {
			return new X509Certificate[0];
		}
	}

	private static class MyHostNameVerifier implements HostnameVerifier {
		public boolean verify(String hostname, SSLSession session) {
			return false;
		}
	}
}