// Code generated by "requestgen -type SubmitOrderRequest -method POST -url /v2/auth/w/order/submit -responseType .SubmitOrderResponse"; DO NOT EDIT.

package bfxapi

import (
	"context"
	"encoding/json"
	"fmt"
	"net/url"
	"reflect"
	"regexp"
)

/*
 * Symbol sets
 */
func (s *SubmitOrderRequest) Symbol(symbol string) *SubmitOrderRequest {
	s.symbol = symbol
	return s
}

/*
 * Amount sets
 */
func (s *SubmitOrderRequest) Amount(amount string) *SubmitOrderRequest {
	s.amount = amount
	return s
}

/*
 * Price sets
 */
func (s *SubmitOrderRequest) Price(price string) *SubmitOrderRequest {
	s.price = &price
	return s
}

/*
 * OrderType sets
 */
func (s *SubmitOrderRequest) OrderType(orderType OrderType) *SubmitOrderRequest {
	s.orderType = orderType
	return s
}

/*
 * PriceAuxLimit sets
 */
func (s *SubmitOrderRequest) PriceAuxLimit(priceAuxLimit string) *SubmitOrderRequest {
	s.priceAuxLimit = &priceAuxLimit
	return s
}

/*
 * PriceOcoStop sets
 */
func (s *SubmitOrderRequest) PriceOcoStop(priceOcoStop string) *SubmitOrderRequest {
	s.priceOcoStop = &priceOcoStop
	return s
}

/*
 * GroupId sets
 */
func (s *SubmitOrderRequest) GroupId(groupId int64) *SubmitOrderRequest {
	s.groupId = &groupId
	return s
}

/*
 * ClientOrderId sets
 */
func (s *SubmitOrderRequest) ClientOrderId(clientOrderId int64) *SubmitOrderRequest {
	s.clientOrderId = &clientOrderId
	return s
}

/*
 * Flags sets
 */
func (s *SubmitOrderRequest) Flags(flags OrderFlag) *SubmitOrderRequest {
	s.flags = &flags
	return s
}

/*
 * Tif sets Time-In-Force: datetime for automatic order cancellation (e.g. 2020-01-15 10:45:23).
 */
func (s *SubmitOrderRequest) Tif(tif string) *SubmitOrderRequest {
	s.tif = &tif
	return s
}

/*
 * Meta sets
 */
func (s *SubmitOrderRequest) Meta(meta Meta) *SubmitOrderRequest {
	s.meta = &meta
	return s
}

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

	query := url.Values{}
	for _k, _v := range params {
		if s.isVarSlice(_v) {
			s.iterateSlice(_v, func(it interface{}) {
				query.Add(_k+"[]", fmt.Sprintf("%v", it))
			})
		} else {
			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 (s *SubmitOrderRequest) GetParameters() (map[string]interface{}, error) {
	var params = map[string]interface{}{}
	// check symbol field -> json key symbol
	symbol := s.symbol

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

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

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

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

		// TEMPLATE check-required
		if len(price) == 0 {
		}
		// END TEMPLATE check-required

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

	// TEMPLATE check-required
	if len(orderType) == 0 {

		orderType = "EXCHANGE LIMIT"
	}
	// END TEMPLATE check-required

	// TEMPLATE check-valid-values
	switch orderType {
	case OrderTypeLimit, OrderTypeExchangeLimit, OrderTypeMarket, OrderTypeExchangeMarket, OrderTypeStop, OrderTypeExchangeStop, OrderTypeStopLimit, OrderTypeExchangeStopLimit, OrderTypeTrailingStop, OrderTypeExchangeTrailingStop, OrderTypeFOK, OrderTypeExchangeFOK, OrderTypeIOC, OrderTypeExchangeIOC:
		params["type"] = orderType

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

	}
	// END TEMPLATE check-valid-values

	// assign parameter of orderType
	params["type"] = orderType
	// check priceAuxLimit field -> json key price_aux_limit
	if s.priceAuxLimit != nil {
		priceAuxLimit := *s.priceAuxLimit

		// TEMPLATE check-required
		if len(priceAuxLimit) == 0 {
		}
		// END TEMPLATE check-required

		// assign parameter of priceAuxLimit
		params["price_aux_limit"] = priceAuxLimit
	} else {
	}
	// check priceOcoStop field -> json key price_oco_stop
	if s.priceOcoStop != nil {
		priceOcoStop := *s.priceOcoStop

		// TEMPLATE check-required
		if len(priceOcoStop) == 0 {
		}
		// END TEMPLATE check-required

		// assign parameter of priceOcoStop
		params["price_oco_stop"] = priceOcoStop
	} else {
	}
	// check groupId field -> json key gid
	if s.groupId != nil {
		groupId := *s.groupId

		// TEMPLATE check-required

		if groupId == 0 {
		}
		// END TEMPLATE check-required

		// assign parameter of groupId
		params["gid"] = groupId
	} else {
	}
	// check clientOrderId field -> json key cid
	if s.clientOrderId != nil {
		clientOrderId := *s.clientOrderId

		// TEMPLATE check-required

		if clientOrderId == 0 {
		}
		// END TEMPLATE check-required

		// assign parameter of clientOrderId
		params["cid"] = clientOrderId
	} else {
	}
	// check flags field -> json key flags
	if s.flags != nil {
		flags := *s.flags

		// TEMPLATE check-required

		if flags == 0 {
		}
		// END TEMPLATE check-required

		// TEMPLATE check-valid-values
		switch flags {
		case OrderFlagHidden, OrderFlagClose, OrderFlagReduceOnly, OrderFlagPostOnly, OrderFlagOCO, OrderFlagNoVarRate:
			params["flags"] = flags

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

		}
		// END TEMPLATE check-valid-values

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

		// TEMPLATE check-required
		if len(tif) == 0 {
		}
		// END TEMPLATE check-required

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

		// TEMPLATE check-required
		// END TEMPLATE check-required

		// assign parameter of meta
		params["meta"] = meta
	} else {
		// assign default of meta

		meta := s.GetDefaultMeta()
		// assign parameter of meta
		params["meta"] = meta
	}

	return params, nil
}

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

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

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

	return params, nil
}

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

func (s *SubmitOrderRequest) GetSlugsMap() (map[string]string, error) {
	slugs := map[string]string{}
	params, err := s.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 (s *SubmitOrderRequest) GetPath() string {
	return "/v2/auth/w/order/submit"
}

// Do generates the request object and send the request object to the API endpoint
func (s *SubmitOrderRequest) Do(ctx context.Context) (*SubmitOrderResponse, error) {

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

	var apiURL string

	apiURL = s.GetPath()

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

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

	var apiResponse SubmitOrderResponse

	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
}
