package common

const JSONRPCVersion = "2.0"

func NewJSONRPCResponse(req JSONRPCRequest, result map[string]interface{}) JSONRPCResponse {
	resp := JSONRPCResponse{Result: result}
	resp.Init(req)
	return resp
}

func NewJSONRPCErrorResponse(code int, message string) JSONRPCErrorResponse {
	err := JSONRPCErrorResponse{}
	err.RPCVersion = JSONRPCVersion
	err.Err(code, message)

	return err
}

type JSONRPCData map[string]interface{}

type JSONRPCBase struct {
	RPCVersion string `json:"jsonrpc" validate:"required,max=10"`
	Method     string `json:"method" validate:"required,max=1000"`
	ID         int    `json:"id" validate:"required,gt=0"`
}

func (b *JSONRPCBase) Init(req JSONRPCRequest) {
	b.RPCVersion = req.RPCVersion
	b.Method = req.Method
	b.ID = req.ID
}

type JSONRPCRequest struct {
	JSONRPCBase
	Params JSONRPCData `json:"params"`
}

type JSONRPCResponse struct {
	JSONRPCBase
	Result JSONRPCData `json:"result"`
}

type JSONRPCErrorResponse struct {
	JSONRPCBase
	Error JSONRPCData `json:"error"`
}

func (e *JSONRPCErrorResponse) Err(code int, message string) {
	e.Error = JSONRPCData{
		"code":    code,
		"message": message,
	}
}
