package binding_context

import (
	"errors"
	"git.sxidc.com/go-tools/api_binding/utils"
	"git.sxidc.com/service-supports/fslog"
	"github.com/gin-gonic/gin"
	"io"
	"mime/multipart"
)

type Context struct {
	*gin.Context
}

// GetPathParams 根据给定的路径参数名字获取参数值
func (c *Context) GetPathParams(pathParamNames []string) ([]string, error) {
	pathParamValues := make([]string, 0)
	for _, paramName := range pathParamNames {
		paramValue := c.Param(paramName)
		if utils.IsStringEmpty(paramValue) {
			return nil, errors.New("没有传递路径参数" + paramName)
		}

		pathParamValues = append(pathParamValues, paramValue)
	}

	return pathParamValues, nil
}

// GetFileHeaderBytes 获取传递的文件名和文件内容
func (c *Context) GetFileHeaderBytes(fileHeader *multipart.FileHeader) (string, []byte, error) {
	file, err := fileHeader.Open()
	if err != nil {
		return "", nil, err
	}

	defer func(file multipart.File) {
		err := file.Close()
		if err != nil {
			fslog.Error(err)
			return
		}
	}(file)

	contentBytes, err := io.ReadAll(file)
	if err != nil {
		return "", nil, err
	}

	return fileHeader.Filename, contentBytes, nil
}