// Package request ...
//
// Description : request ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2022-07-03 00:33
package request

import (
	"bytes"
	"errors"
	"io"
	"net/http"
	"strings"

	"git.zhangdeman.cn/zhangdeman/wrapper/op_array"
	"github.com/mcuadros/go-defaults"

	"github.com/go-playground/validator/v10"

	"git.zhangdeman.cn/zhangdeman/gin/define"

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

// form 表单相关操作
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 00:51 2022/7/3
type form struct {
	checkInstance *validator.Validate
}

// Parse 解析请求表单
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 00:34 2022/7/3
func (f *form) Parse(ctx *gin.Context, receiver interface{}) error {
	handleConfig := define.GetHttpHandleConfig()
	requestBody, _ := io.ReadAll(ctx.Request.Body)
	// 请求信息写入上下文
	ctx.Set(handleConfig.RecordRequestDataField, string(requestBody))
	// 因为请求体被读一遍之后就没了，重新赋值 requestBody
	ctx.Request.Body = io.NopCloser(bytes.NewReader(requestBody))
	method := strings.ToUpper(ctx.Request.Method)
	if op_array.ArrayType([]string{
		http.MethodGet, http.MethodPatch, http.MethodTrace, http.MethodConnect, http.MethodOptions,
	}).Has(method) >= 0 {
		if err := ctx.ShouldBindQuery(receiver); nil != err {
			return err
		}
	} else if method == http.MethodPost ||
		method == http.MethodPut ||
		method == http.MethodDelete {
		if ContentType.IsJson(ctx) {
			if err := ctx.ShouldBindJSON(receiver); nil != err {
				return err
			}
		} else if ContentType.IsFormURLEncoded(ctx) {
			if err := ctx.ShouldBind(receiver); nil != err {
				return err
			}
		} else {
			return errors.New(ctx.ContentType() + " is not support")
		}
	} else {
		return errors.New(method + " : request method is not support")
	}
	// 设置默认值
	defaults.SetDefaults(receiver)
	return nil
}
