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 PreauthorisationRedirectCard {
	public static void preauthorisationRedirectExample(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(Utils.randomString(12));

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

            // OK / KO
//            params.setUrlOk(host + "/frontend/preauthorisation/card/redirect/success.html?amount=" + params.getAmount() + "&order=" + params.getOrder() + "&a=a");
            params.setUrlKo(host + "/frontend/error.html");
            params.setUrlOk(host + "/frontend/success.html?amount=" + receivedParams.get("amount") 
		  		+ "&order=" + params.getOrder() + "&method=redirect"
		  		+ "&transactionType=" + TransactionType.PREAUTHORISATION + "&a=a");
        }
		
		final String redirectForm = GenerateRedirectForm.preauthorisation(merchant, params);
		Server.renderHtml(exchange, redirectForm);
	}
	
	public static void preauthorisationConfirmationRedirectExample(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=preauthorisationConfirmationRedirectExample");

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