package be.fgov.ehealth.technicalconnector.tests.server.callback;

import be.ehealth.technicalconnector.utils.ConnectorIOUtils;
import org.apache.commons.lang3.StringUtils;
import org.mockserver.model.HttpRequest;
import org.mockserver.model.HttpResponse;

import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;

public class ContentExpectationCallback extends AbstractExpectationCallback {

    private static Map<String, Queue<String>> content = new HashMap<>();

    @Override
    public HttpResponse handle(HttpRequest httpRequest) {
        try {
            String body = content.get(httpRequest.getPath().getValue()).poll();
            if (!StringUtils.startsWith(body, "<")) {
                body = ConnectorIOUtils.getResourceAsString(body);
            }
            return HttpResponse.response()
                    .withStatusCode(200)
                    .withHeader("Content-Type", "text/xml")
                    .withBody(body);
        } catch (Exception e) {
            return internalError(e.getMessage(), e);
        }
    }


    public static void add(String path, String location) {
        if (!content.containsKey(path)) {
            content.put(path, new ArrayDeque<>());
        }
        content.get(path).add(location);
    }

    public static void reset() {
        content.clear();
    }
}
