// Code generated by "requestgen -method GET -url /products/:product_id/candles -rateLimiter 1+20/2s -type GetCandlesRequest -responseType .GetCandlesResponse"; DO NOT EDIT.

package coinbase

import (
	"context"
	"encoding/json"
	"fmt"
	"golang.org/x/time/rate"
	"net/url"
	"reflect"
	"regexp"
	"strconv"
	"time"
)

var GetCandlesRequestLimiter = rate.NewLimiter(10, 1)

func (g *GetCandlesRequest) Granularity(granularity string) *GetCandlesRequest {
	g.granularity = &granularity
	return g
}

func (g *GetCandlesRequest) Start(start time.Time) *GetCandlesRequest {
	g.start = &start
	return g
}

func (g *GetCandlesRequest) End(end time.Time) *GetCandlesRequest {
	g.end = &end
	return g
}

func (g *GetCandlesRequest) ProductID(productID string) *GetCandlesRequest {
	g.productID = productID
	return g
}

// GetQueryParameters builds and checks the query parameters and returns url.Values
func (g *GetCandlesRequest) GetQueryParameters() (url.Values, error) {
	var params = map[string]interface{}{}

	query := url.Values{}
	for _k, _v := range params {
		query.Add(_k, fmt.Sprintf("%v", _v))
	}

	return query, nil
}

// GetParameters builds and checks the parameters and return the result in a map object
func (g *GetCandlesRequest) GetParameters() (map[string]interface{}, error) {
	var params = map[string]interface{}{}
	// check granularity field -> json key granularity
	if g.granularity != nil {
		granularity := *g.granularity

		// TEMPLATE check-valid-values
		switch granularity {
		case "60", "300", "900", "3600", "21600", "86400":
			params["granularity"] = granularity

		default:
			return nil, fmt.Errorf("granularity value %v is invalid", granularity)

		}
		// END TEMPLATE check-valid-values

		// assign parameter of granularity
		params["granularity"] = granularity
	} else {
	}
	// check start field -> json key start
	if g.start != nil {
		start := *g.start

		// assign parameter of start
		// convert time.Time to seconds time stamp
		params["start"] = strconv.FormatInt(start.Unix(), 10)
	} else {
	}
	// check end field -> json key end
	if g.end != nil {
		end := *g.end

		// assign parameter of end
		// convert time.Time to seconds time stamp
		params["end"] = strconv.FormatInt(end.Unix(), 10)
	} else {
	}

	return params, nil
}

// GetParametersQuery converts the parameters from GetParameters into the url.Values format
func (g *GetCandlesRequest) GetParametersQuery() (url.Values, error) {
	query := url.Values{}

	params, err := g.GetParameters()
	if err != nil {
		return query, err
	}

	for _k, _v := range params {
		if g.isVarSlice(_v) {
			g.iterateSlice(_v, func(it interface{}) {
				query.Add(_k+"[]", fmt.Sprintf("%v", it))
			})
		} else {
			query.Add(_k, fmt.Sprintf("%v", _v))
		}
	}

	return query, nil
}

// GetParametersJSON converts the parameters from GetParameters into the JSON format
func (g *GetCandlesRequest) GetParametersJSON() ([]byte, error) {
	params, err := g.GetParameters()
	if err != nil {
		return nil, err
	}

	return json.Marshal(params)
}

// GetSlugParameters builds and checks the slug parameters and return the result in a map object
func (g *GetCandlesRequest) GetSlugParameters() (map[string]interface{}, error) {
	var params = map[string]interface{}{}
	// check productID field -> json key product_id
	productID := g.productID

	// TEMPLATE check-required
	if len(productID) == 0 {
		return nil, fmt.Errorf("product_id is required, empty string given")
	}
	// END TEMPLATE check-required

	// assign parameter of productID
	params["product_id"] = productID

	return params, nil
}

func (g *GetCandlesRequest) applySlugsToUrl(url string, slugs map[string]string) string {
	for _k, _v := range slugs {
		needleRE := regexp.MustCompile(":" + _k + "\\b")
		url = needleRE.ReplaceAllString(url, _v)
	}

	return url
}

func (g *GetCandlesRequest) iterateSlice(slice interface{}, _f func(it interface{})) {
	sliceValue := reflect.ValueOf(slice)
	for _i := 0; _i < sliceValue.Len(); _i++ {
		it := sliceValue.Index(_i).Interface()
		_f(it)
	}
}

func (g *GetCandlesRequest) isVarSlice(_v interface{}) bool {
	rt := reflect.TypeOf(_v)
	switch rt.Kind() {
	case reflect.Slice:
		return true
	}
	return false
}

func (g *GetCandlesRequest) GetSlugsMap() (map[string]string, error) {
	slugs := map[string]string{}
	params, err := g.GetSlugParameters()
	if err != nil {
		return slugs, nil
	}

	for _k, _v := range params {
		slugs[_k] = fmt.Sprintf("%v", _v)
	}

	return slugs, nil
}

// GetPath returns the request path of the API
func (g *GetCandlesRequest) GetPath() string {
	return "/products/:product_id/candles"
}

// Do generates the request object and send the request object to the API endpoint
func (g *GetCandlesRequest) Do(ctx context.Context) (GetCandlesResponse, error) {
	if err := GetCandlesRequestLimiter.Wait(ctx); err != nil {
		return nil, err
	}

	// empty params for GET operation
	var params interface{}
	query, err := g.GetParametersQuery()
	if err != nil {
		return nil, err
	}

	var apiURL string

	apiURL = g.GetPath()
	slugs, err := g.GetSlugsMap()
	if err != nil {
		return nil, err
	}

	apiURL = g.applySlugsToUrl(apiURL, slugs)

	req, err := g.client.NewAuthenticatedRequest(ctx, "GET", apiURL, query, params)
	if err != nil {
		return nil, err
	}

	response, err := g.client.SendRequest(req)
	if err != nil {
		return nil, err
	}

	var apiResponse GetCandlesResponse

	type responseUnmarshaler interface {
		Unmarshal(data []byte) error
	}

	if unmarshaler, ok := interface{}(&apiResponse).(responseUnmarshaler); ok {
		if err := unmarshaler.Unmarshal(response.Body); err != nil {
			return nil, err
		}
	} else {
		// The line below checks the content type, however, some API server might not send the correct content type header,
		// Hence, this is commented for backward compatibility
		// response.IsJSON()
		if err := response.DecodeJSON(&apiResponse); err != nil {
			return nil, err
		}
	}

	type responseValidator interface {
		Validate() error
	}

	if validator, ok := interface{}(&apiResponse).(responseValidator); ok {
		if err := validator.Validate(); err != nil {
			return nil, err
		}
	}
	return apiResponse, nil
}
