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

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

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.mockserver.model.HttpRequest;
import org.mockserver.model.HttpResponse;
import org.mockserver.model.Parameter;

import be.ehealth.technicalconnector.utils.ConnectorIOUtils;

public class FullExpectationCallback extends AbstractExpectationCallback {

    private Queue<String> content = new ArrayDeque<String>();

    @Override
    public HttpResponse handle(HttpRequest httpRequest) {
        try {
            String location = content.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.getQueryStringParameters()){
                    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 void add(String location){
        content.add(location);
    }


}
