package metrics

import (
	"io/ioutil"
	"net/http"

	"github.com/tidwall/gjson"
)

// JSONSelector using GJSON to get value from a complex JSON. it provides a
// very simple yet powerful syntax to declarative retrieve value.
// Check out https://github.com/tidwall/gjson#path-syntax for an overview.
// There's a set of examples in pkg/matcher/metrics/api_test.go.
//
// Note that this func may return nil under three different conditions.
//
// For a single http.Response, JSONSelector could select on ONLY ONCE.
// If you need select multiple JSON value, use pd.GetJSONBytes to retrieve bytes first
// then call gjson.GetBytes.
//
// Deprecated: in favor of pd.GetJSONBytes & gjson.GetBytes.
func JSONSelector(resp *http.Response, jsonPath string) interface{} {
	bytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil
	}
	if !gjson.ValidBytes(bytes) {
		return nil
	}
	return gjson.GetBytes(bytes, jsonPath).Value()
}
