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

import dev.fyloz.trial.colorrecipesexplorer.web.response.ModelResponseBuilder;
import dev.fyloz.trial.colorrecipesexplorer.web.response.ResponseCode;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;

import static dev.fyloz.trial.colorrecipesexplorer.web.WebsitePaths.ERROR;

@Controller
@Profile("thymeleaf")
public class CREErrorController implements ErrorController {

    @RequestMapping("/error")
    public ModelAndView handleError(HttpServletRequest request) {
        ModelResponseBuilder responseBuilder = new ModelResponseBuilder("error");
        responseBuilder.addAttribute("referer", request.getHeader("referer"));

        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);

        ResponseCode responseCode = ResponseCode._500;
        if (status != null) {
            int statusCode = Integer.parseInt(status.toString());

            switch (statusCode) {
                case 401:
                    responseCode = ResponseCode._401;
                    break;
                case 404:
                    responseCode = ResponseCode._404;
                    break;
                default:
                    responseCode = ResponseCode._500;
                    break;
            }
        }

        responseBuilder.addResponseCode(responseCode);
        return responseBuilder.build();
    }

    @Override
    public String getErrorPath() {
        return ERROR;
    }

}
