package demo.examples.redirect;

import java.io.IOException;
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.TransactionType;
import es.redsys.lib.Utils;

public class AuthenticationRedirectCard {
	
	public static void authenticationRedirectExample(HttpExchange exchange) throws IOException {
		Server.addCors(exchange);
		  
		final Merchant merchant = Merchant.initWithApiKey(Secrets.REDSYS_API_KEY);
		final Parameters params = new Parameters();
		
		final Map<String, String> receivedParams = Server.getQueryParams(exchange);
		params.putExtra("DS_MERCHANT_AMOUNT", receivedParams.get("amount"));
		params.putExtra("DS_MERCHANT_ORDER", Utils.randomString(12));

        final String host = Server.getSchemeAndHost(exchange);
        if(host != null && !host.trim().isEmpty()) {
            // Notification
        	params.putExtra("DS_MERCHANT_MERCHANTURL", host + "/backend/card/notification?origin=authenticationRedirectExample");

            // OK / KO
        	params.putExtra("DS_MERCHANT_URLKO", host + "/frontend/error.html");
        	params.putExtra("DS_MERCHANT_URLOK", host + "/frontend/success.html?amount=" + params.getStringExtra("DS_MERCHANT_AMOUNT") 
    			+ "&order=" + params.getStringExtra("DS_MERCHANT_ORDER") + "&method=redirect"
    			+ "&transactionType=" + TransactionType.AUTHENTICATION + "&a=a");
        }
		
		final String redirectForm = GenerateRedirectForm.authentication(merchant, params);
		Server.renderHtml(exchange, redirectForm);
	}
	
	public static void authenticationConfirmationRedirectExample(HttpExchange exchange) throws IOException {
		Server.addCors(exchange);
		  
		final Merchant merchant = Merchant.initWithApiKey(Secrets.REDSYS_API_KEY);
		final Parameters params = new Parameters();
		
		final Map<String, String> receivedParams = Server.getQueryParams(exchange);
		params.setAmount(receivedParams.get("amount"));
		params.setOrder(receivedParams.get("order"));

        final String host = Server.getSchemeAndHost(exchange);
        if(host != null && !host.trim().isEmpty()) {
            // Notification
            params.setMerchantUrl(host + "/backend/card/notification?origin=authenticationConfirmationRedirectExample");

            // OK / KO
            params.setUrlOk(host + "/frontend/success.html?amount=" + receivedParams.get("amount") 
            	+ "&order=" + receivedParams.get("order") + "&method=redirect"
            	+ "&transactionType=" + TransactionType.AUTHENTICATION_CONFIRMATION + "&a=a");
            params.setUrlKo(host + "/frontend/error.html");
        }
		
		final String redirectForm = GenerateRedirectForm.authenticationConfirmation(merchant, params);
		Server.renderHtml(exchange, redirectForm);
	}
}
