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

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

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

public class FullExpectationCallback extends AbstractExpectationCallback {

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

    @Override
    public HttpResponse handle(HttpRequest httpRequest) {
        try {
            String location = content.get(httpRequest.getPath().getValue()).poll();
            Properties props = new Properties();
            props.loadFromXML(ConnectorIOUtils.getResourceAsStream(location));
            if (props.containsKey("txt")) {
                String[] searchList = ArrayUtils.EMPTY_STRING_ARRAY;
                String[] replacementList = ArrayUtils.EMPTY_STRING_ARRAY;
                for (Parameter param : httpRequest.getPathParameterList()) {
                    searchList = (String[]) ArrayUtils.add(searchList, "${" + param.getName().getValue() + "}");
                    replacementList = (String[]) ArrayUtils.add(replacementList, param.getValues().get(0).getValue());
                }
                String body = StringUtils.replaceEach(props.getProperty("txt"), searchList, replacementList);
                return HttpResponse.response()
                        .withStatusCode(Integer.valueOf(props.getProperty("status")))
                        .withHeader("Content-Type", props.get("mimeType").toString())
                        .withBody(body);
            } else {
                return HttpResponse.response()
                        .withStatusCode(Integer.valueOf(props.getProperty("status")))
                        .withHeader("Content-Type", props.get("mimeType").toString())
                        .withBody(ConnectorIOUtils.getResourceAsByteArray(props.getProperty("location")));
            }
        } 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();
    }
}
