package cn.edu.tju.se.base.web;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
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 org.springframework.web.bind.annotation.RestController;

import cn.edu.tju.se.base.domain.Dict;
import cn.edu.tju.se.base.exception.*;
import cn.edu.tju.se.base.service.DictService;

@RestController
@ControllerAdvice  
public class ApiExceptionHandler {  
  
	@Autowired DictService dictService;
	
	private Logger logger ;
	
    public ApiExceptionHandler() {
    	logger = LoggerFactory.getLogger(ApiExceptionHandler.class);   
	}

	@ExceptionHandler(NotFoundException.class)  
    @ResponseStatus(value = HttpStatus.NOT_FOUND)  
    @ResponseBody  
    public String handleNotFoundEexception(NotFoundException ex) {  
    	logger.error("My Exception LOGGING..."+ex.getMessage());    	
        return ex.getMessage();  
    }  
  
	@ExceptionHandler(MyException.class)  
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)  
    @ResponseBody  
    public Dict handleMyExceptionError(MyException ex) {  
    	logger.error("My Exception LOGGING..."+ex.getMessage());  
    	List<Dict> dicts = dictService.getByTypeAndNumber("error", ex.getErrorCode() );
    	Dict dict = null;
    	if (dicts!=null&&dicts.size()==1){
    		dict = dicts.get(0);
    	}
        return dict;//ex.getMessage();  
    }  
	
    @ExceptionHandler(NumberFormatException.class)  
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)  
    @ResponseBody  
    public String handleNumberFormastException(NumberFormatException ex) {
    	System.out.println(ex);
    	logger.error("NumberFormatException LOGGING..."+ex.getMessage());
        return ex.getMessage();  
    }  
    
    @ExceptionHandler(UsernameNotFoundException.class)  
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)  
    @ResponseBody  
    public String handleUsernameNotFoundException(UsernameNotFoundException ex) {
    	System.out.println(ex);
    	logger.error("UsernameNotFoundException LOGGING..."+ex.getMessage());
        return ex.getMessage();  
    }  
}  