package com.izouma.zhirongip.web;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

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

@Controller
public class AppErrorController implements ErrorController {
    @Override
    public String getErrorPath() {
        return "/error";
    }

    @RequestMapping("/error")
    public String handleError(HttpServletRequest request, Model model) {
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);

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

            if (statusCode == HttpStatus.NOT_FOUND.value()) {
                return "commons/404";
            } else if (statusCode == HttpStatus.UNAUTHORIZED.value()) {
                return "commons/401";
            } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                return "commons/500";
            }
        }
        return "commons/error";
    }

    @RequestMapping("/401")
    public String error401() {
        return "commons/401";
    }

    @RequestMapping("/404")
    public String error404() {
        return "commons/404";
    }

    @RequestMapping("/500")
    public String error500() {
        return "commons/500";
    }
}
