package dp.kotul.starter.util

import com.fasterxml.jackson.annotation.JsonIgnore
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.context.request.WebRequest
import org.springframework.web.servlet.HandlerMapping
import java.util.Date

data class ApiError(
        val timestamp: Date = Date(),
        @JsonIgnore
        val httpStatus: HttpStatus,
        val status: Int = httpStatus.value(),
        val error: String = httpStatus.reasonPhrase,
        val message: String,
        val path: String? = null,
        val params: Any? = null
) {
        constructor(status: HttpStatus, message: String, request: WebRequest, params: Any? = null) : this(
                httpStatus = status,
                message = message,
                path = request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, 0) as String?,
                params = params
        )

        constructor(status: HttpStatus, ex: Throwable, request: WebRequest, params: Any? = null) : this(
                status = status,
                message = ex.localizedMessage,
                request = request,
                params = params
        )

        constructor(status: HttpStatus, message: String, params: Any? = null) : this(
                httpStatus = status,
                message = message,
                params = params
        )

        fun responseEntity(): ResponseEntity<Any> = ResponseEntity(this, httpStatus)
}
