// Code generated by "requestgen -method POST -responseType .APIResponse -responseDataField Data -url /api/v2/spot/trade/place-order -type PlaceOrderRequest -responseDataType .PlaceOrderResponse"; DO NOT EDIT.

package bitgetapi

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/c9s/bbgo/pkg/exchange/bitget/bitgetapi"
	"net/url"
	"reflect"
	"regexp"
)

func (p *PlaceOrderRequest) Symbol(symbol string) *PlaceOrderRequest {
	p.symbol = symbol
	return p
}

func (p *PlaceOrderRequest) OrderType(orderType OrderType) *PlaceOrderRequest {
	p.orderType = orderType
	return p
}

func (p *PlaceOrderRequest) Side(side SideType) *PlaceOrderRequest {
	p.side = side
	return p
}

func (p *PlaceOrderRequest) Force(force OrderForce) *PlaceOrderRequest {
	p.force = force
	return p
}

func (p *PlaceOrderRequest) Price(price string) *PlaceOrderRequest {
	p.price = &price
	return p
}

func (p *PlaceOrderRequest) Size(size string) *PlaceOrderRequest {
	p.size = size
	return p
}

func (p *PlaceOrderRequest) ClientOrderId(clientOrderId string) *PlaceOrderRequest {
	p.clientOrderId = &clientOrderId
	return p
}

// GetQueryParameters builds and checks the query parameters and returns url.Values
func (p *PlaceOrderRequest) 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 (p *PlaceOrderRequest) GetParameters() (map[string]interface{}, error) {
	var params = map[string]interface{}{}
	// check symbol field -> json key symbol
	symbol := p.symbol

	// assign parameter of symbol
	params["symbol"] = symbol
	// check orderType field -> json key orderType
	orderType := p.orderType

	// TEMPLATE check-valid-values
	switch orderType {
	case OrderTypeLimit, OrderTypeMarket:
		params["orderType"] = orderType

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

	}
	// END TEMPLATE check-valid-values

	// assign parameter of orderType
	params["orderType"] = orderType
	// check side field -> json key side
	side := p.side

	// TEMPLATE check-valid-values
	switch side {
	case SideTypeBuy, SideTypeSell:
		params["side"] = side

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

	}
	// END TEMPLATE check-valid-values

	// assign parameter of side
	params["side"] = side
	// check force field -> json key force
	force := p.force

	// TEMPLATE check-valid-values
	switch force {
	case OrderForceGTC, OrderForcePostOnly, OrderForceFOK, OrderForceIOC:
		params["force"] = force

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

	}
	// END TEMPLATE check-valid-values

	// assign parameter of force
	params["force"] = force
	// check price field -> json key price
	if p.price != nil {
		price := *p.price

		// assign parameter of price
		params["price"] = price
	} else {
	}
	// check size field -> json key size
	size := p.size

	// assign parameter of size
	params["size"] = size
	// check clientOrderId field -> json key clientOid
	if p.clientOrderId != nil {
		clientOrderId := *p.clientOrderId

		// assign parameter of clientOrderId
		params["clientOid"] = clientOrderId
	} else {
	}

	return params, nil
}

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

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

	for _k, _v := range params {
		if p.isVarSlice(_v) {
			p.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 (p *PlaceOrderRequest) GetParametersJSON() ([]byte, error) {
	params, err := p.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 (p *PlaceOrderRequest) GetSlugParameters() (map[string]interface{}, error) {
	var params = map[string]interface{}{}

	return params, nil
}

func (p *PlaceOrderRequest) 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 (p *PlaceOrderRequest) 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 (p *PlaceOrderRequest) isVarSlice(_v interface{}) bool {
	rt := reflect.TypeOf(_v)
	switch rt.Kind() {
	case reflect.Slice:
		return true
	}
	return false
}

func (p *PlaceOrderRequest) GetSlugsMap() (map[string]string, error) {
	slugs := map[string]string{}
	params, err := p.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 (p *PlaceOrderRequest) GetPath() string {
	return "/api/v2/spot/trade/place-order"
}

// Do generates the request object and send the request object to the API endpoint
func (p *PlaceOrderRequest) Do(ctx context.Context) (*PlaceOrderResponse, error) {

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

	var apiURL string

	apiURL = p.GetPath()

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

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

	var apiResponse bitgetapi.APIResponse

	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
		}
	}
	var data PlaceOrderResponse
	if err := json.Unmarshal(apiResponse.Data, &data); err != nil {
		return nil, err
	}
	return &data, nil
}
