package link.at17.mid.tushare.web.exception;

import org.springframework.http.HttpStatus;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

/**
 * 抛出该异常，返回带状态码的 R
 * 
 * @author Doghole
 * @see link.at17.mid.tushare.dto.R
 * @see link.at17.mid.tushare.web.exception.TushareWebPlatformExceptionHandler
 *
 */
@Data
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = false)
@AllArgsConstructor
public class RException extends RuntimeException {

    private static final long serialVersionUID = -4140809043470089887L;

    private HttpStatus httpStatus;

    private Boolean logRequest = false;

    public RException(HttpStatus status) {
        super((String) null);
        this.httpStatus = status;
    }

    public RException(HttpStatus status, String message) {
        super(message);
        this.httpStatus = status;
    }

    public static RException badRequest() {
        return new RException(HttpStatus.BAD_REQUEST);
    }

    public static RException badRequest(String message) {
        return new RException(HttpStatus.BAD_REQUEST, message);
    }
    
    public static RException badRequest(Object... message) {
        if (message == null || message.length == 0) {
            return RException.badRequest();
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < message.length; i++) {
            sb.append(message[i]);
        }
        return new RException(HttpStatus.BAD_REQUEST, sb.toString());
    }

    public static RException unauthorized() {
        return new RException(HttpStatus.UNAUTHORIZED);
    }

    public static RException unauthorized(String message) {
        return new RException(HttpStatus.UNAUTHORIZED, message);
    }

    public static RException unauthorized(Object... message) {
        if (message == null || message.length == 0) {
            return RException.unauthorized();
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < message.length; i++) {
            sb.append(message[i]);
        }
        return new RException(HttpStatus.UNAUTHORIZED, sb.toString());
    }
    
    public static RException internalServerError() {
        return new RException(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    public static RException internalServerError(String message) {
        return new RException(HttpStatus.INTERNAL_SERVER_ERROR, message);
    }

    public static RException internalServerError(Object... message) {
        if (message == null || message.length == 0) {
            return RException.internalServerError();
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < message.length; i++) {
            sb.append(message[i]);
        }
        return new RException(HttpStatus.INTERNAL_SERVER_ERROR, sb.toString());
    }
}
