// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package array

import (
	
	
	
	
	

	
	
	
	
	
)

// Timestamp represents an immutable sequence of arrow.Timestamp values.
type Timestamp struct {
	array
	values []arrow.Timestamp
}

// NewTimestampData creates a new Timestamp from Data.
func ( arrow.ArrayData) *Timestamp {
	 := &Timestamp{}
	.refCount.Add(1)
	.setData(.(*Data))
	return 
}

// Reset resets the array for re-use.
func ( *Timestamp) ( *Data) {
	.setData()
}

// Value returns the value at the specified index.
func ( *Timestamp) ( int) arrow.Timestamp { return .values[] }

func ( *Timestamp) () []arrow.Timestamp { return .values }

// TimestampValues returns the values.
func ( *Timestamp) () []arrow.Timestamp { return .Values() }

// String returns a string representation of the array.
func ( *Timestamp) () string {
	 := new(strings.Builder)
	.WriteString("[")
	for ,  := range .values {
		if  > 0 {
			fmt.Fprintf(, " ")
		}
		switch {
		case .IsNull():
			.WriteString(NullValueStr)
		default:
			fmt.Fprintf(, "%v", )
		}
	}
	.WriteString("]")
	return .String()
}

func ( *Timestamp) ( *Data) {
	.array.setData()
	 := .buffers[1]
	if  != nil {
		.values = arrow.TimestampTraits.CastFromBytes(.Bytes())
		 := .data.offset
		 :=  + .data.length
		.values = .values[:]
	}
}

func ( *Timestamp) ( int) string {
	if .IsNull() {
		return NullValueStr
	}

	,  := .DataType().(*arrow.TimestampType).GetToTimeFunc()
	return (.values[]).Format(time.RFC3339Nano)
}

func ( *Timestamp) ( int) interface{} {
	if  := .ValueStr();  != NullValueStr {
		return 
	}
	return nil
}

func ( *Timestamp) () ([]byte, error) {
	 := make([]interface{}, .Len())
	for  := range .values {
		[] = .GetOneForMarshal()
	}

	return json.Marshal()
}

func arrayEqualTimestamp(,  *Timestamp) bool {
	for  := 0;  < .Len(); ++ {
		if .IsNull() {
			continue
		}
		if .Value() != .Value() {
			return false
		}
	}
	return true
}

type TimestampBuilder struct {
	builder

	dtype   *arrow.TimestampType
	data    *memory.Buffer
	rawData []arrow.Timestamp
}

func ( memory.Allocator,  *arrow.TimestampType) *TimestampBuilder {
	 := &TimestampBuilder{builder: builder{mem: }, dtype: }
	.refCount.Add(1)
	return 
}

func ( *TimestampBuilder) () arrow.DataType { return .dtype }

// Release decreases the reference count by 1.
// When the reference count goes to zero, the memory is freed.
func ( *TimestampBuilder) () {
	debug.Assert(.refCount.Load() > 0, "too many releases")

	if .refCount.Add(-1) == 0 {
		if .nullBitmap != nil {
			.nullBitmap.Release()
			.nullBitmap = nil
		}
		if .data != nil {
			.data.Release()
			.data = nil
			.rawData = nil
		}
	}
}

func ( *TimestampBuilder) ( time.Time) {
	,  := arrow.TimestampFromTime(, .dtype.Unit)
	if  != nil {
		panic()
	}
	.Append()
}

func ( *TimestampBuilder) ( arrow.Timestamp) {
	.Reserve(1)
	.UnsafeAppend()
}

func ( *TimestampBuilder) () {
	.Reserve(1)
	.UnsafeAppendBoolToBitmap(false)
}

func ( *TimestampBuilder) ( int) {
	for  := 0;  < ; ++ {
		.AppendNull()
	}
}

func ( *TimestampBuilder) () {
	.Append(0)
}

func ( *TimestampBuilder) ( int) {
	for  := 0;  < ; ++ {
		.AppendEmptyValue()
	}
}

func ( *TimestampBuilder) ( arrow.Timestamp) {
	bitutil.SetBit(.nullBitmap.Bytes(), .length)
	.rawData[.length] = 
	.length++
}

func ( *TimestampBuilder) ( bool) {
	if  {
		bitutil.SetBit(.nullBitmap.Bytes(), .length)
	} else {
		.nulls++
	}
	.length++
}

// AppendValues will append the values in the v slice. The valid slice determines which values
// in v are valid (not null). The valid slice must either be empty or be equal in length to v. If empty,
// all values in v are appended and considered valid.
func ( *TimestampBuilder) ( []arrow.Timestamp,  []bool) {
	if len() != len() && len() != 0 {
		panic("len(v) != len(valid) && len(valid) != 0")
	}

	if len() == 0 {
		return
	}

	.Reserve(len())
	arrow.TimestampTraits.Copy(.rawData[.length:], )
	.unsafeAppendBoolsToBitmap(, len())
}

func ( *TimestampBuilder) ( int) {
	.builder.init()

	.data = memory.NewResizableBuffer(.mem)
	 := arrow.TimestampTraits.BytesRequired()
	.data.Resize()
	.rawData = arrow.TimestampTraits.CastFromBytes(.data.Bytes())
}

// Reserve ensures there is enough space for appending n elements
// by checking the capacity and calling Resize if necessary.
func ( *TimestampBuilder) ( int) {
	.reserve(, .Resize)
}

// Resize adjusts the space allocated by b to n elements. If n is greater than b.Cap(),
// additional memory will be allocated. If n is smaller, the allocated memory may reduced.
func ( *TimestampBuilder) ( int) {
	 := 
	if  < minBuilderCapacity {
		 = minBuilderCapacity
	}

	if .capacity == 0 {
		.init()
	} else {
		.resize(, .init)
		.data.Resize(arrow.TimestampTraits.BytesRequired())
		.rawData = arrow.TimestampTraits.CastFromBytes(.data.Bytes())
	}
}

// NewArray creates a Timestamp array from the memory buffers used by the builder and resets the TimestampBuilder
// so it can be used to build a new array.
func ( *TimestampBuilder) () arrow.Array {
	return .NewTimestampArray()
}

// NewTimestampArray creates a Timestamp array from the memory buffers used by the builder and resets the TimestampBuilder
// so it can be used to build a new array.
func ( *TimestampBuilder) () ( *Timestamp) {
	 := .newData()
	 = NewTimestampData()
	.Release()
	return
}

func ( *TimestampBuilder) () ( *Data) {
	 := arrow.TimestampTraits.BytesRequired(.length)
	if  > 0 &&  < .data.Len() {
		// trim buffers
		.data.Resize()
	}
	 = NewData(.dtype, .length, []*memory.Buffer{.nullBitmap, .data}, nil, .nulls, 0)
	.reset()

	if .data != nil {
		.data.Release()
		.data = nil
		.rawData = nil
	}

	return
}

func ( *TimestampBuilder) ( string) error {
	if  == NullValueStr {
		.AppendNull()
		return nil
	}

	,  := .dtype.GetZone()
	if  != nil {
		return 
	}

	, ,  := arrow.TimestampFromStringInLocation(, .dtype.Unit, )
	if  != nil {
		.AppendNull()
		return 
	}
	.Append()
	return nil
}

func ( *TimestampBuilder) ( *json.Decoder) error {
	,  := .Token()
	if  != nil {
		return 
	}

	switch v := .(type) {
	case nil:
		.AppendNull()
	case string:
		,  := .dtype.GetZone()
		, ,  := arrow.TimestampFromStringInLocation(, .dtype.Unit, )
		if  != nil {
			return &json.UnmarshalTypeError{
				Value:  ,
				Type:   reflect.TypeOf(arrow.Timestamp(0)),
				Offset: .InputOffset(),
			}
		}

		.Append()
	case json.Number:
		,  := .Int64()
		if  != nil {
			return &json.UnmarshalTypeError{
				Value:  .String(),
				Type:   reflect.TypeOf(arrow.Timestamp(0)),
				Offset: .InputOffset(),
			}
		}
		.Append(arrow.Timestamp())
	case float64:
		.Append(arrow.Timestamp())

	default:
		return &json.UnmarshalTypeError{
			Value:  fmt.Sprint(),
			Type:   reflect.TypeOf(arrow.Timestamp(0)),
			Offset: .InputOffset(),
		}
	}

	return nil
}

func ( *TimestampBuilder) ( *json.Decoder) error {
	for .More() {
		if  := .UnmarshalOne();  != nil {
			return 
		}
	}
	return nil
}

func ( *TimestampBuilder) ( []byte) error {
	 := json.NewDecoder(bytes.NewReader())
	,  := .Token()
	if  != nil {
		return 
	}

	if ,  := .(json.Delim); ! ||  != '[' {
		return fmt.Errorf("binary builder must unpack from json array, found %s", )
	}

	return .Unmarshal()
}

var (
	_ arrow.Array                       = (*Timestamp)(nil)
	_ Builder                           = (*TimestampBuilder)(nil)
	_ arrow.TypedArray[arrow.Timestamp] = (*Timestamp)(nil)
)