package demo.examples.rest;

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.Merchant;
import es.redsys.lib.Parameters;
import es.redsys.lib.PaymentMethod;
import es.redsys.lib.Response;
import es.redsys.lib.Rest;

public class RefundRestBizum {
	public static void refundRestExample(HttpExchange exchange) throws IOException {
		Server.addCors(exchange);

		final Merchant merchant = Merchant.initWithApiKey(Secrets.REDSYS_API_KEY);
		final Parameters params = new Parameters();
		
		final Map<String, Object> receivedParams = Server.getJsonParams(exchange);
		params.setAmount(String.valueOf(receivedParams.get("amount")).replace(",", "").replace(".", ""));
		params.setOrder(String.valueOf(receivedParams.get("order"))); 
		params.setPayMethods(PaymentMethod.BIZUM);

        final String host = Server.getSchemeAndHost(exchange);
        if(host != null && !host.trim().isEmpty()) {
            // Notification
            params.setMerchantUrl(host + "/backend/card/notification?origin=refundRestExample");
        }
 
		Response response2 = new Response();
		try {
			response2 = Rest.refund(merchant, params);
			if((response2.getErrorCode() != null && !response2.getErrorCode().trim().isEmpty()) || 900 != Integer.valueOf(response2.getData().getCodResponse())) {
				throw new Exception();
			}

	      } catch (Exception e) {
	      	Server.jsonResponse(exchange, 400, response2.toJsonNoAnnotations());        	
	      }

		Server.jsonResponse(exchange, 200, response2.toJsonNoAnnotations());   
	}
}
