package com.oqpo.api.web.controller;

import com.oqpo.api.enums.SystemMessageCode;
import com.oqpo.api.exception.GlobalException;
import com.oqpo.api.exception.UnauthorizedException;
import com.oqpo.api.web.dto.ExceptionDTO;

import lombok.extern.slf4j.Slf4j;

import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.List;
import java.util.stream.Collectors;

@ControllerAdvice
@ResponseBody
@Slf4j
public class ApiExceptionHandler {
	@ExceptionHandler(DataAccessException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    protected ExceptionDTO handleException(HttpServletRequest request, DataAccessException e) {
        log.error(e.getMessage());
		//e.printStackTrace();
		
        return ExceptionDTO.builder()
            .status(HttpStatus.INTERNAL_SERVER_ERROR.value())
            .message(SystemMessageCode.SERVER_ERR.getMessage())
            .path(request.getRequestURI())
            .build();
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    protected ExceptionDTO handleMethodArgumentNotValidException(HttpServletRequest request, MethodArgumentNotValidException e) {
        log.error(e.getMessage());
        //e.printStackTrace();
        final BindingResult bindingResult = e.getBindingResult();
        final List<FieldError> errors = bindingResult.getFieldErrors();

        return ExceptionDTO.builder()
            .status(HttpStatus.BAD_REQUEST.value())
            .message(e.getMessage())
            .path(request.getRequestURI())
            .errors(errors.parallelStream()
                .map(error -> ExceptionDTO.FieldError.builder()
                    .reason(error.getDefaultMessage())
                    .field(error.getField())
                    .value((String) error.getRejectedValue())
                    .build())
                .collect(Collectors.toList()))
            .build();
    }
	
	/*
    @ExceptionHandler(SessionNotFoundException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    protected ExceptionDTO handleSessionNotFoundException(SessionNotFoundException e) {
        return ExceptionDTO.builder()
            .status(HttpStatus.UNAUTHORIZED.value())
            .message(e.getMessage())
            .build();
    }
	*/
	
    @ExceptionHandler(GlobalException.class)
    protected ResponseEntity<Object> handleGlobalException(HttpServletRequest request, GlobalException e) {
        log.error(e.getMessage());
        //e.printStackTrace();

        if (e.getSystemMessageCode() != null) {
            SystemMessageCode systemMessageCode = e.getSystemMessageCode();

            ExceptionDTO body = ExceptionDTO.builder()
                    .code(String.valueOf(systemMessageCode.getId()))
                    .message(String.valueOf(systemMessageCode.getMessage()))
                    .path(request.getRequestURI())
                    .build();

            return new ResponseEntity<>(body, e.getSystemMessageCode().getHttpStatus());
        } else {
            ExceptionDTO body = ExceptionDTO.builder()
                    .code(e.getErrorCode())
                    .message(e.getMessage())
                    .path(request.getRequestURI())
                    .build();

            return new ResponseEntity<>(body, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    protected ExceptionDTO handleException(Exception e, HttpServletRequest request, HttpServletResponse response) {
        log.error(e.getMessage());
        //e.printStackTrace();
		
        return ExceptionDTO.builder()
                .status(HttpStatus.INTERNAL_SERVER_ERROR.value())
                .message(SystemMessageCode.SERVER_ERR.getMessage())
                .path(request.getRequestURI())
                .build();
    }

    @ExceptionHandler(UnauthorizedException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    protected ExceptionDTO handleUnauthorizedException(Exception e, HttpServletRequest request, HttpServletResponse response) {
        log.error("handleUnauthorizedException");
        //e.printStackTrace();
		
        return ExceptionDTO.builder()
            .status(HttpStatus.UNAUTHORIZED.value())
            .message(e.getMessage())
            .path(request.getRequestURI())
            .build();
    }
}
