package sgc.portal.base.error;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequest;

import java.util.List;
import java.util.Map;

/**
 * The type Resolved message error attributes.
 *
 * @author YongSang
 */
@Component
public class ResolvedMessageErrorAttributes extends DefaultErrorAttributes {
    @Autowired
    private List<ErrorMessageResolver> errorMessageResolvers;
    
    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
        Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, includeStackTrace);
        Throwable t = getError(webRequest);
        String message = resolveErrorMessage(t);
        errorAttributes.put("message", (message == null) ? errorAttributes.get("message") : message);
        return errorAttributes;
    }

    /**
     * Client에 보여줄 에러 메시지를 적절하게 생성하여 리턴
     *
     * @param error 예외 객체
     * @return 에러 메시지
     */
    private String resolveErrorMessage(Throwable error) {
        if (error != null) {
            for (ErrorMessageResolver errorMessageResolver : errorMessageResolvers) {
                if (errorMessageResolver.supports(error)) {
                    return errorMessageResolver.resolveErrorMessage(error);
                }
            }
        }
        return "No message available";
    }
}