/* Copyright 2017 Avaya LLC. All rights reserved. */
package sample;

import java.io.IOException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.xml.bind.DatatypeConverter;

import org.glassfish.jersey.SslConfigurator;

import com.avaya.asm.mgmt.model.rs.RsError;

public class Common {
	static public String URLBASE = "https://turtlebay7.dr.avaya.com/ASM/ws";
	static public String ADMINID = "admin";
	static public String ADMINPASSWORD = "Admin123$";
	
	static public void checkError(Response response) throws Exception {
		System.out.println("Response content: " + response.toString());
		if (response.getStatus() >= 400) {
			System.out.println("Got an error");
			System.out.println(response.toString());
			if (response.getLength() > 0) {
				RsError err = response.readEntity(RsError.class);
				printRsError(err);
			}
			throw new Exception(response.toString());
		}
	}
	
	static public void printRsError(RsError err) {
		System.out.println("RsError.err.getRequestURI(): " + err.getRequestURI());
		System.out.println("RsError.err.err.getRequestMethod(): " + err.getRequestMethod());
		System.out.println("RsError.getMessage(): " + err.getMessage());	
	}
	
	/**
	 * Trust everything, not recommended.
	 * 
	 * @return
	 * @throws Exception
	 */
	static public SSLContext getTrustedContext() throws Exception {
		System.err.println("In getTrustedContext");
		TrustManager[] tm = new TrustManager[] { new X509TrustManager() {
			@Override
			public X509Certificate[] getAcceptedIssuers() {
				return null;
			}

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

			@Override
			public void checkClientTrusted(X509Certificate[] chain,
					String authType) throws CertificateException {
			}
		} };

		SSLContext ctx = null;
		ctx = SSLContext.getInstance("TLS");
		ctx.init(null, tm, new SecureRandom());
		return ctx;
	}
	
	public static class BasicAuth implements ClientRequestFilter {
	    private final String user;
	    private final String password;

	    public BasicAuth(String user, String password) {
	        this.user = user;
	        this.password = password;
	    }

	    public void filter(ClientRequestContext requestContext) throws IOException {
	        MultivaluedMap<String, Object> headers = requestContext.getHeaders();
	        final String basicAuthentication = getBasicAuthentication();
	        headers.add("Authorization", basicAuthentication);
	    }

	    private String getBasicAuthentication() {
	        String token = this.user + ":" + this.password;
	        try {
	            return "BASIC " + DatatypeConverter.printBase64Binary(token.getBytes("UTF-8"));
	        } catch (Exception ex) {
	            throw new IllegalStateException("Cannot encode with UTF-8", ex);
	        }
	    }
	}
	
	static public ClientRequestFilter getAuthFilter() {
		return new BasicAuth(ADMINID, ADMINPASSWORD);
	}
	
	static public Client getClient() {
		SslConfigurator sslConfig = SslConfigurator.newInstance().trustStoreFile("./resources/sample.jks").trustStorePassword("sample").securityProtocol("TLS");
		SSLContext sslContext = sslConfig.createSSLContext();
		Client client = ClientBuilder.newBuilder().sslContext(sslContext).register(getAuthFilter()).build();
		return client;
	}

}
