// Code generated by meshRPC. DO NOT EDIT.
// All changes must be done in custom client that should either embed or wrap this.

package greeter

import (
	"encoding/json"

	"github.com/astranet/httpserve"
)

type RPCHandler interface {
	Greet(*httpserve.Context) httpserve.Response
	SendPostcard(*httpserve.Context) httpserve.Response
}

var RPCHandlerSpec RPCHandler = &rpcHandler{}

type RPCHandlerOptions struct {
}

func checkRPCHandlerOptions(opt *RPCHandlerOptions) *RPCHandlerOptions {
	if opt == nil {
		opt = &RPCHandlerOptions{}
	}
	return opt
}

func NewRPCHandler(
	svc Service,
	opt *RPCHandlerOptions,
) RPCHandler {
	return &rpcHandler{
		opt: checkRPCHandlerOptions(opt),
		svc: svc,
	}
}

type rpcHandler struct {
	svc Service
	opt *RPCHandlerOptions
}

type GreetRequest struct {
	Name string `json:"name,omitempty"`
}

type GreetResponse struct {
	Message string `json:"message,omitempty"`
}

func (_handler *rpcHandler) Greet(_ctx *httpserve.Context) (_res httpserve.Response) {
	// TODO: Report Stats + Timing

	var _req GreetRequest
	_decoder := json.NewDecoder(_ctx.Request.Body)
	defer _ctx.Request.Body.Close()
	_err := _decoder.Decode(&_req)
	if _err != nil {
		// TODO: Report Error

		_res = httpserve.NewJSONResponse(400, _err)
		return
	}
	var _resp GreetResponse
	_resp.Message, _err = _handler.svc.Greet(_req.Name)
	if _err != nil {
		// TODO: Report Error

		_res = httpserve.NewJSONResponse(400, _err)
		return
	}

	_res = httpserve.NewJSONResponse(200, &_resp)
	return
}

type SendPostcardRequest struct {
	Card *Postcard `json:"card,omitempty"`
}

type SendPostcardResponse struct {
}

func (_handler *rpcHandler) SendPostcard(_ctx *httpserve.Context) (_res httpserve.Response) {
	// TODO: Report Stats + Timing

	var _req SendPostcardRequest
	_decoder := json.NewDecoder(_ctx.Request.Body)
	defer _ctx.Request.Body.Close()
	_err := _decoder.Decode(&_req)
	if _err != nil {
		// TODO: Report Error

		_res = httpserve.NewJSONResponse(400, _err)
		return
	}
	var _resp SendPostcardResponse
	_err = _handler.svc.SendPostcard(_req.Card)
	if _err != nil {
		// TODO: Report Error

		_res = httpserve.NewJSONResponse(400, _err)
		return
	}

	_res = httpserve.NewJSONResponse(200, &_resp)
	return
}

var rpcHandlerMethodsMap = map[string][]string{
	"*": []string{
		"POST",
	},
}

func (_ *rpcHandler) HTTPMethodsMap() map[string][]string {
	return rpcHandlerMethodsMap
}

type ErrorResponse struct {
	Error string `json:"error"`
}
