package dev.fyloz.trial.colorrecipesexplorer.web.controller.thymeleaf

import dev.fyloz.trial.colorrecipesexplorer.web.response.ResponseCode
import dev.fyloz.trial.colorrecipesexplorer.utils.ControllerUtils
import org.springframework.web.servlet.ModelAndView

fun modelAndView(model: ModelAndView = ModelAndView(), op: ModelAndView.() -> Unit = {}) = model.apply {
    addObject("baseUrl", ControllerUtils.getCurrentBaseUrl())
    addObject("referer", ControllerUtils.getLatestUrl())
    apply(op)
}

fun modelAndView(viewName: String, op: ModelAndView.() -> Unit = {}) = modelAndView(ModelAndView(viewName), op)

fun ModelAndView.message(responseCode: ResponseCode, vararg parameters: Any?) {
    addObject(if (responseCode.type == ResponseCode.ResponseCodeType.ERROR) "error" else "success", "response.${responseCode.code}")
    parameters.forEachIndexed { index, param ->
        addObject("responseArg${index + 1}", param)
    }
}
