package jsonrpc2

import (
	"encoding/json"
	"fmt"
)

var (
	errServerError = NewError(-1, "Error: json.Marshal failed")
)

// Error represent JSON-RPC 2.0 "Error object".
type Error struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

// NewError returns an Error with given code and message.
func NewError(code int, message string) *Error {
	return &Error{Code: code, Message: message}
}

// NewError returns an Error with given code and message.
func NewJsonError(code int, message string) error {
	e := &Error{Code: code, Message: message}
	buf, err := json.Marshal(e)
	if err != nil {
		msg, err := json.Marshal(err.Error())
		if err != nil {
			msg = []byte(`"` + errServerError.Message + `"`)
		}
		return fmt.Errorf(`{"code":%d,"message":%s}`, errServerError.Code, string(msg))
	}
	return fmt.Errorf(string(buf))

}

// Error returns JSON representation of Error.
func (e *Error) Error() string {
	buf, err := json.Marshal(e)
	if err != nil {
		msg, err := json.Marshal(err.Error())
		if err != nil {
			msg = []byte(`"` + errServerError.Message + `"`)
		}
		return fmt.Sprintf(`{"code":%d,"message":%s}`, errServerError.Code, string(msg))
	}
	return string(buf)
}
