package handler

import (
	"net/http"
	"youngee_b_api/consts"
	"youngee_b_api/util"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

type BaseHandler interface {
	getContext() *gin.Context
	getResponse() interface{}
	getRequest() interface{}
	run()
	checkParam() error
}

func baseRun(baseHandler BaseHandler) {
	ctx := baseHandler.getContext()
	method := ctx.Request.Method
	req := baseHandler.getRequest()
	var err error
	if method == http.MethodPost || method == http.MethodPut {
		err = ctx.ShouldBindJSON(req)
	} else if method == http.MethodGet {
		err = ctx.BindQuery(req)
	}
	if err != nil {
		util.PackErrorResp(ctx, consts.ErrorParamCheck)
		ctx.Abort()
		logrus.Infof("[baseHandler] bind json error,err:%+v", err)
		return
	}
	if err = baseHandler.checkParam(); err != nil {
		util.PackErrorResp(ctx, consts.ErrorParamCheck)
		ctx.Abort()
		logrus.Infof("[baseHandler] checkParam error,err:%+v", err)
		return
	}
	baseHandler.run()
	if ctx.IsAborted() {
		return
	}
	resp := baseHandler.getResponse()
	ctx.JSON(http.StatusOK, resp)
	logrus.Infof("[baseHandler] http success")
}
