/*
 * Subset of Influx API covered by Influx CLI
 *
 * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
 *
 * API version: 2.0.0
 */

// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.

package api

import (
	_context "context"
	_fmt "fmt"
	_io "io"
	_nethttp "net/http"
	_neturl "net/url"
)

// Linger please
var (
	_ _context.Context
)

type WriteApi interface {

	/*
			 * PostWrite Write data
			 * Writes data to a bucket.

		Use this endpoint to send data in [line protocol]({{% INFLUXDB_DOCS_URL %}}/reference/syntax/line-protocol/) format to InfluxDB.

		#### InfluxDB Cloud

		- Does the following when you send a write request:

		  1. Validates the request and queues the write.
		  2. If queued, responds with _success_ (HTTP `2xx` status code); _error_ otherwise.
		  3. Handles the delete asynchronously and reaches eventual consistency.

		  To ensure that InfluxDB Cloud handles writes and deletes in the order you request them,
		  wait for a success response (HTTP `2xx` status code) before you send the next request.

		  Because writes and deletes are asynchronous, your change might not yet be readable
		  when you receive the response.

		#### InfluxDB OSS

		- Validates the request and handles the write synchronously.
		- If all points were written successfully, responds with HTTP `2xx` status code;
		  otherwise, returns the first line that failed.

		#### Required permissions

		- `write-buckets` or `write-bucket BUCKET_ID`.

		 *`BUCKET_ID`* is the ID of the destination bucket.

		#### Rate limits (with InfluxDB Cloud)

		`write` rate limits apply.
		For more information, see [limits and adjustable quotas](https://docs.influxdata.com/influxdb/cloud/account-management/limits/).

		#### Related guides

		- [Write data with the InfluxDB API]({{% INFLUXDB_DOCS_URL %}}/write-data/developer-tools/api)
		- [Optimize writes to InfluxDB]({{% INFLUXDB_DOCS_URL %}}/write-data/best-practices/optimize-writes/)
		- [Troubleshoot issues writing data]({{% INFLUXDB_DOCS_URL %}}/write-data/troubleshoot/)

			 * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
			 * @return ApiPostWriteRequest
	*/
	PostWrite(ctx _context.Context) ApiPostWriteRequest

	/*
	 * PostWriteExecute executes the request
	 */
	PostWriteExecute(r ApiPostWriteRequest) error

	/*
	 * PostWriteExecuteWithHttpInfo executes the request with HTTP response info returned. The response body is not
	 * available on the returned HTTP response as it will have already been read and closed; access to the response body
	 * content should be achieved through the returned response model if applicable.
	 */
	PostWriteExecuteWithHttpInfo(r ApiPostWriteRequest) (*_nethttp.Response, error)
}

// WriteApiService WriteApi service
type WriteApiService service

type ApiPostWriteRequest struct {
	ctx             _context.Context
	ApiService      WriteApi
	org             *string
	bucket          *string
	body            []byte
	zapTraceSpan    *string
	contentEncoding *string
	contentType     *string
	contentLength   *int32
	accept          *string
	orgID           *string
	precision       *WritePrecision
}

func (r ApiPostWriteRequest) Org(org string) ApiPostWriteRequest {
	r.org = &org
	return r
}
func (r ApiPostWriteRequest) GetOrg() *string {
	return r.org
}

func (r ApiPostWriteRequest) Bucket(bucket string) ApiPostWriteRequest {
	r.bucket = &bucket
	return r
}
func (r ApiPostWriteRequest) GetBucket() *string {
	return r.bucket
}

func (r ApiPostWriteRequest) Body(body []byte) ApiPostWriteRequest {
	r.body = body
	return r
}
func (r ApiPostWriteRequest) GetBody() []byte {
	return r.body
}

func (r ApiPostWriteRequest) ZapTraceSpan(zapTraceSpan string) ApiPostWriteRequest {
	r.zapTraceSpan = &zapTraceSpan
	return r
}
func (r ApiPostWriteRequest) GetZapTraceSpan() *string {
	return r.zapTraceSpan
}

func (r ApiPostWriteRequest) ContentEncoding(contentEncoding string) ApiPostWriteRequest {
	r.contentEncoding = &contentEncoding
	return r
}
func (r ApiPostWriteRequest) GetContentEncoding() *string {
	return r.contentEncoding
}

func (r ApiPostWriteRequest) ContentType(contentType string) ApiPostWriteRequest {
	r.contentType = &contentType
	return r
}
func (r ApiPostWriteRequest) GetContentType() *string {
	return r.contentType
}

func (r ApiPostWriteRequest) ContentLength(contentLength int32) ApiPostWriteRequest {
	r.contentLength = &contentLength
	return r
}
func (r ApiPostWriteRequest) GetContentLength() *int32 {
	return r.contentLength
}

func (r ApiPostWriteRequest) Accept(accept string) ApiPostWriteRequest {
	r.accept = &accept
	return r
}
func (r ApiPostWriteRequest) GetAccept() *string {
	return r.accept
}

func (r ApiPostWriteRequest) OrgID(orgID string) ApiPostWriteRequest {
	r.orgID = &orgID
	return r
}
func (r ApiPostWriteRequest) GetOrgID() *string {
	return r.orgID
}

func (r ApiPostWriteRequest) Precision(precision WritePrecision) ApiPostWriteRequest {
	r.precision = &precision
	return r
}
func (r ApiPostWriteRequest) GetPrecision() *WritePrecision {
	return r.precision
}

func (r ApiPostWriteRequest) Execute() error {
	return r.ApiService.PostWriteExecute(r)
}

func (r ApiPostWriteRequest) ExecuteWithHttpInfo() (*_nethttp.Response, error) {
	return r.ApiService.PostWriteExecuteWithHttpInfo(r)
}

/*
  - PostWrite Write data
  - Writes data to a bucket.

Use this endpoint to send data in [line protocol]({{% INFLUXDB_DOCS_URL %}}/reference/syntax/line-protocol/) format to InfluxDB.

#### InfluxDB Cloud

- Does the following when you send a write request:

 1. Validates the request and queues the write.

 2. If queued, responds with _success_ (HTTP `2xx` status code); _error_ otherwise.

 3. Handles the delete asynchronously and reaches eventual consistency.

    To ensure that InfluxDB Cloud handles writes and deletes in the order you request them,
    wait for a success response (HTTP `2xx` status code) before you send the next request.

    Because writes and deletes are asynchronous, your change might not yet be readable
    when you receive the response.

#### InfluxDB OSS

  - Validates the request and handles the write synchronously.
  - If all points were written successfully, responds with HTTP `2xx` status code;
    otherwise, returns the first line that failed.

#### Required permissions

- `write-buckets` or `write-bucket BUCKET_ID`.

	*`BUCKET_ID`* is the ID of the destination bucket.

#### Rate limits (with InfluxDB Cloud)

`write` rate limits apply.
For more information, see [limits and adjustable quotas](https://docs.influxdata.com/influxdb/cloud/account-management/limits/).

#### Related guides

- [Write data with the InfluxDB API]({{% INFLUXDB_DOCS_URL %}}/write-data/developer-tools/api)
- [Optimize writes to InfluxDB]({{% INFLUXDB_DOCS_URL %}}/write-data/best-practices/optimize-writes/)
- [Troubleshoot issues writing data]({{% INFLUXDB_DOCS_URL %}}/write-data/troubleshoot/)

  - @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
  - @return ApiPostWriteRequest
*/
func (a *WriteApiService) PostWrite(ctx _context.Context) ApiPostWriteRequest {
	return ApiPostWriteRequest{
		ApiService: a,
		ctx:        ctx,
	}
}

/*
 * Execute executes the request
 */
func (a *WriteApiService) PostWriteExecute(r ApiPostWriteRequest) error {
	_, err := a.PostWriteExecuteWithHttpInfo(r)
	return err
}

/*
 * ExecuteWithHttpInfo executes the request with HTTP response info returned. The response body is not available on the
 * returned HTTP response as it will have already been read and closed; access to the response body content should be
 * achieved through the returned response model if applicable.
 */
func (a *WriteApiService) PostWriteExecuteWithHttpInfo(r ApiPostWriteRequest) (*_nethttp.Response, error) {
	var (
		localVarHTTPMethod   = _nethttp.MethodPost
		localVarPostBody     interface{}
		localVarFormFileName string
		localVarFileName     string
		localVarFileBytes    []byte
	)

	localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "WriteApiService.PostWrite")
	if err != nil {
		return nil, GenericOpenAPIError{error: err.Error()}
	}

	localVarPath := localBasePath + "/api/v2/write"

	localVarHeaderParams := make(map[string]string)
	localVarQueryParams := _neturl.Values{}
	localVarFormParams := _neturl.Values{}
	if r.org == nil {
		return nil, reportError("org is required and must be specified")
	}
	if r.bucket == nil {
		return nil, reportError("bucket is required and must be specified")
	}
	if r.body == nil {
		return nil, reportError("body is required and must be specified")
	}

	localVarQueryParams.Add("org", parameterToString(*r.org, ""))
	if r.orgID != nil {
		localVarQueryParams.Add("orgID", parameterToString(*r.orgID, ""))
	}
	localVarQueryParams.Add("bucket", parameterToString(*r.bucket, ""))
	if r.precision != nil {
		localVarQueryParams.Add("precision", parameterToString(*r.precision, ""))
	}
	// to determine the Content-Type header
	localVarHTTPContentTypes := []string{"text/plain"}

	// set Content-Type header
	localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
	if localVarHTTPContentType != "" {
		localVarHeaderParams["Content-Type"] = localVarHTTPContentType
	}

	// to determine the Accept header
	localVarHTTPHeaderAccepts := []string{"application/json", "text/html"}

	// set Accept header
	localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
	if localVarHTTPHeaderAccept != "" {
		localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
	}
	if r.zapTraceSpan != nil {
		localVarHeaderParams["Zap-Trace-Span"] = parameterToString(*r.zapTraceSpan, "")
	}
	if r.contentEncoding != nil {
		localVarHeaderParams["Content-Encoding"] = parameterToString(*r.contentEncoding, "")
	}
	if r.contentType != nil {
		localVarHeaderParams["Content-Type"] = parameterToString(*r.contentType, "")
	}
	if r.contentLength != nil {
		localVarHeaderParams["Content-Length"] = parameterToString(*r.contentLength, "")
	}
	if r.accept != nil {
		localVarHeaderParams["Accept"] = parameterToString(*r.accept, "")
	}
	// body params
	localVarPostBody = r.body
	req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
	if err != nil {
		return nil, err
	}

	localVarHTTPResponse, err := a.client.callAPI(req)
	if err != nil || localVarHTTPResponse == nil {
		return localVarHTTPResponse, err
	}

	newErr := GenericOpenAPIError{
		buildHeader: localVarHTTPResponse.Header.Get("X-Influxdb-Build"),
	}

	if localVarHTTPResponse.StatusCode >= 300 {
		body, err := GunzipIfNeeded(localVarHTTPResponse)
		if err != nil {
			body.Close()
			newErr.error = err.Error()
			return localVarHTTPResponse, newErr
		}
		localVarBody, err := _io.ReadAll(body)
		body.Close()
		if err != nil {
			newErr.error = err.Error()
			return localVarHTTPResponse, newErr
		}
		newErr.body = localVarBody
		newErr.error = localVarHTTPResponse.Status
		if localVarHTTPResponse.StatusCode == 400 {
			var v LineProtocolError
			err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
			if err != nil {
				newErr.error = _fmt.Sprintf("%s: %s", newErr.Error(), err.Error())
				return localVarHTTPResponse, newErr
			}
			v.SetMessage(_fmt.Sprintf("%s: %s", newErr.Error(), v.GetMessage()))
			newErr.model = &v
			return localVarHTTPResponse, newErr
		}
		if localVarHTTPResponse.StatusCode == 401 {
			var v UnauthorizedRequestError
			err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
			if err != nil {
				newErr.error = _fmt.Sprintf("%s: %s", newErr.Error(), err.Error())
				return localVarHTTPResponse, newErr
			}
			v.SetMessage(_fmt.Sprintf("%s: %s", newErr.Error(), v.GetMessage()))
			newErr.model = &v
			return localVarHTTPResponse, newErr
		}
		if localVarHTTPResponse.StatusCode == 413 {
			var v LineProtocolLengthError
			err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
			if err != nil {
				newErr.error = _fmt.Sprintf("%s: %s", newErr.Error(), err.Error())
				return localVarHTTPResponse, newErr
			}
			v.SetMessage(_fmt.Sprintf("%s: %s", newErr.Error(), v.GetMessage()))
			newErr.model = &v
			return localVarHTTPResponse, newErr
		}
		var v Error
		err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
		if err != nil {
			newErr.error = _fmt.Sprintf("%s: %s", newErr.Error(), err.Error())
			return localVarHTTPResponse, newErr
		}
		v.SetMessage(_fmt.Sprintf("%s: %s", newErr.Error(), v.GetMessage()))
		newErr.model = &v
		return localVarHTTPResponse, newErr
	}

	return localVarHTTPResponse, nil
}
