package dev.fyloz.trial.colorrecipesexplorer.web.response;

import org.springframework.web.servlet.ModelAndView;

public class ModelResponseBuilder extends ResponseBuilder<ModelResponseBuilder, ModelAndView> {

    private static final String PATH_PARAMETER_PATTERN = "(\\{\\w+\\})";
    private static final String REDIRECT_PATH_PREFIX = "redirect:/";

    private ModelAndView model;

    public ModelResponseBuilder() {
        this.model = new ModelAndView();
    }

    public ModelResponseBuilder(String view) {
        this(new ModelAndView(view));
    }

    public ModelResponseBuilder(ModelAndView model) {
        this.model = model == null ? new ModelAndView() : model;
    }

    public ModelResponseBuilder withView(String path) {
        model.setViewName(path);

        return this;
    }

    public ModelResponseBuilder withView(String path, Object... parameters) {
        path = replaceInPath(path, parameters);
        model.setViewName(path);

        return this;
    }

    public ModelResponseBuilder withRedirect(String path, Object... parameters) {
        return withView(REDIRECT_PATH_PREFIX + path, parameters);
    }

    @Override
    protected void addResponseCodeToAttribute(String responseCodeType, String responseMessagePath, String[] parameters) {
        addAttribute(responseCodeType, responseMessagePath);

        for (int i = 0; i < parameters.length; i++) {
            addAttribute(String.format("responseArg%s", i + 1), parameters[i]);
        }
    }

    public ModelAndView build() {
        model.addAllObjects(attributes);

        return model;
    }

    private String replaceInPath(String path, Object... parameters) {
        for (Object parameter : parameters) {
            path = path.replaceFirst(PATH_PARAMETER_PATTERN, parameter.toString());
        }

        return path;
    }
}
