package demo.examples.rest;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
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.Merchant;
import es.redsys.lib.Parameters;
import es.redsys.lib.Utils;

public class ReceiveNotification {

    public static void handle(HttpExchange exchange, final Merchant merchant) throws IOException {
        try {
            final Map<String, Object> receivedParams = Server.getFormParams(exchange);

            final String origin = String.valueOf(receivedParams.getOrDefault("origin", ""));
            final Parameters params = Parameters.digest(merchant, receivedParams);

            final String notificationString =
                    origin + ": " + params.toJson() + System.lineSeparator();

            String projectRoot = System.getProperty("user.dir");
            Path logsDir = Paths.get(projectRoot, "logs");
            Files.createDirectories(logsDir);

            Path logFile = logsDir.resolve("notificationLog.txt");

            Files.write(
                logFile,
                notificationString.getBytes(StandardCharsets.UTF_8),
                StandardOpenOption.CREATE,
                StandardOpenOption.APPEND
            );


            final Map<String, Object> status = new HashMap<String, Object>();
            status.put("status", "ok");
            Server.jsonResponse(exchange, 200, Utils.mapToJson(status));

        } catch (Exception e) {
            final Map<String, Object> status = new HashMap<String, Object>();
            status.put("status", "error");
            status.put("message", e.getMessage());
            Server.jsonResponse(exchange, 200, Utils.mapToJson(status));
        }
    }
	
    public static void handleCard(HttpExchange exchange) throws IOException {
        final Merchant merchant = Merchant.initWithApiKey(Secrets.REDSYS_API_KEY);
    	handle(exchange, merchant);
    }
    
    public static void handleBizum(HttpExchange exchange) throws IOException {
        final Merchant merchant = Merchant.initWithApiKey(Secrets.REDSYS_API_KEY);
    	handle(exchange, merchant);
    }
}
