package cfg

import (
	"encoding/json"
	"mtp2_if/global/app"
	"mtp2_if/global/e"
	"net/http"
	"os"

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

// QueryCfg 查询终端配置
func QueryCfg(c *gin.Context) {
	appG := app.Gin{C: c}

	// 获取请求参数
	key := appG.C.Query("key")
	if key == "" {
		appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
		return
	}

	// 读取json文件
	filePtr, err := os.Open("config/cfg.json")
	if err != nil {
		appG.Response(http.StatusBadRequest, e.ERROR_CFG_FILE_FAIL, nil)
		return
	}
	defer filePtr.Close()

	var datas map[string]interface{}
	// 创建Json编码器
	decoder := json.NewDecoder(filePtr)
	if err = decoder.Decode(&datas); err != nil {
		appG.Response(http.StatusBadRequest, e.ERROR_CFG_JSON_FAIL, nil)
		return
	}

	// 获取指定key的配置内容
	if _, ok := datas[key]; !ok {
		appG.Response(http.StatusBadRequest, e.ERROR_CFG_KEY_FAIL, nil)
		return
	}

	appG.Response(http.StatusOK, e.SUCCESS, datas[key])
}
