package demo.examples.rest;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import com.sun.net.httpserver.HttpExchange;

import demo.config.Secrets;
import demo.server.Server;
import es.redsys.lib.GenerateRedirectForm;
import es.redsys.lib.Merchant;
import es.redsys.lib.Parameters;
import es.redsys.lib.Response;
import es.redsys.lib.Rest;
import es.redsys.lib.TransactionType;
import es.redsys.lib.Utils;

public class ChallengeResponse {
	public static void challengeResponseExample(HttpExchange exchange) throws IOException {
		Server.addCors(exchange);

		final Map<String, Object> receivedParams = Server.getFormParams(exchange);
		if(receivedParams.get("cres") == null) {
			Server.serverRedirect(exchange, "/frontend/error.html", 302);
		}
		
        final String host = Server.getSchemeAndHost(exchange);
		final Map<String, String> receivedQueryParams = Server.getQueryParams(exchange);

		final Merchant merchant = Merchant.initWithApiKey(Secrets.REDSYS_API_KEY);
		final Parameters params = new Parameters();
		params.setOrder(receivedQueryParams.get("order"));

		final Map<String, Object> emv3ds = new HashMap<String, Object>();
		emv3ds.put("protocolVersion", receivedQueryParams.get("protocolVersion"));
		emv3ds.put("cres", receivedParams.get("cres"));
		emv3ds.put("threeDSInfo", "ChallengeResponse");
		params.setEmv3ds(emv3ds);
		
		Response challengeResponse = null;
		try {
			challengeResponse = Rest.challengeResponse(merchant, params);
			if(challengeResponse != null && challengeResponse.getData() != null && "0000".equals(challengeResponse.getData().getCodResponse())) {
				final String path = "/frontend/success.html?amount=" + receivedQueryParams.get("amount") + "&order=" + params.getOrder() 
				+ "&method=rest&transactionType=" + receivedQueryParams.get("transactionType") + "&a=a";
				
				Server.serverRedirect(exchange, path, 302);
			} else {
				throw new Exception("Error");
			}
		} catch (Exception e) {
		    String urlToRedirect = host + "/frontend/error.html?a=a";
		    if(challengeResponse != null) {
			    if(challengeResponse.getErrorCode() != null) {
			        urlToRedirect += "&errorCode=" + challengeResponse.getErrorCode();
			    }
			    if(challengeResponse.getDescription() != null) {
			        urlToRedirect += "&description=" + challengeResponse.getDescription();
			    }
			    if(challengeResponse.getRaw() != null) {
			    	urlToRedirect += "&response=" + URLEncoder.encode(challengeResponse.getRaw(), "UTF-8");
			    }
		    }
		    
			Server.serverRedirect(exchange, urlToRedirect, 302);
		}		
	}
}
