// 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
	layout           string
	useDefaultLayout bool
}

const timestampNoTimezoneLayout = "2006-01-02T15:04:05.999999999"

// NewTimestampData creates a new Timestamp from Data.
func ( arrow.ArrayData) *Timestamp {
	return newTimestampDataWithValueStrLayout(, "", true)
}

// NewTimestampDataWithValueStrLayout creates a new Timestamp from Data with a custom ValueStr layout.
// The layout is passed to the time.Time.Format method.
// This is useful for cases where consumers expect a non standard layout
func ( arrow.ArrayData,  string) *Timestamp {
	return newTimestampDataWithValueStrLayout(, , false)
}

func newTimestampDataWithValueStrLayout( arrow.ArrayData,  string,  bool) *Timestamp {
	 := &Timestamp{layout: , useDefaultLayout: }
	.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()
	if  != nil {
		return "..."
	}
	 := (.values[])
	if .useDefaultLayout && (.Year() < 0 || .Year() > 9999) {
		return strconv.FormatInt(int64(.values[]), 10)
	}
	 := .layout
	if .useDefaultLayout {
		 = time.RFC3339Nano
		if .TimeZone == "" {
			 = timestampNoTimezoneLayout
		} else if ,  := .Zone(); %60 != 0 {
			 = timestampNoTimezoneLayout + "Z07:00:00"
		}
	}
	return .Format()
}

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

func ( *Timestamp) ( int) any {
	if .IsNull() {
		return nil
	}
	return .Value()
}

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

	return json.Marshal()
}

func arrayEqualTimestamp(,  *Timestamp) bool {
	return arrayEqualFixedWidth(, )
}

type TimestampBuilder struct {
	builder

	dtype            *arrow.TimestampType
	data             *memory.Buffer
	rawData          []arrow.Timestamp
	layout           string
	useDefaultLayout bool
}

func ( memory.Allocator,  *arrow.TimestampType) *TimestampBuilder {
	return newTimestampBuilderWithValueStrLayout(, , "", true)
}

// NewTimestampBuilderWithValueStrLayout creates a new TimestampBuilder with a custom ValueStr layout.
// The layout is passed to the time.Time.Format method.
// This is useful for cases where consumers expect a non standard layout
func ( memory.Allocator,  *arrow.TimestampType,  string) *TimestampBuilder {
	return newTimestampBuilderWithValueStrLayout(, , , false)
}

func newTimestampBuilderWithValueStrLayout( memory.Allocator,  *arrow.TimestampType,  string,  bool) *TimestampBuilder {
	 := &TimestampBuilder{
		builder:          builder{mem: },
		dtype:            ,
		layout:           ,
		useDefaultLayout: ,
	}
	.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) {
	if  <= 0 {
		return
	}
	if  == 1 {
		.AppendNull()
		return
	}
	.Reserve()
	.unsafeAppendNulls()
}

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

func ( *TimestampBuilder) ( int) {
	if  <= 0 {
		return
	}
	if  == 1 {
		.AppendEmptyValue()
		return
	}
	.Reserve()
	.unsafeAppendEmptyValues(.data.Bytes(), arrow.TimestampTraits.BytesRequired(1), )
}

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()
	 = newTimestampDataWithValueStrLayout(, .layout, .useDefaultLayout)
	.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 {
	,  := .dtype.GetZone()
	if  != nil {
		return 
	}

	if  == NullValueStr {
		.AppendNull()
		return nil
	}

	if ,  := strconv.ParseInt(, 10, 64);  == nil {
		.Append(arrow.Timestamp())
		return nil
	}

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

	if  != (.dtype.TimeZone != "") {
		.AppendNull()
		if .dtype.TimeZone != "" {
			return fmt.Errorf("%w: timestamp value %q for type %s must include a zone offset", arrow.ErrInvalid, , .dtype)
		}
		return fmt.Errorf("%w: timestamp value %q for type %s must not include a zone offset", arrow.ErrInvalid, , .dtype)
	}

	.Append()
	return nil
}

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

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

	switch v := .(type) {
	case nil:
		.AppendNull()
	case string:
		if ,  := strconv.ParseInt(, 10, 64);  == nil {
			.Append(arrow.Timestamp())
			break
		}
		, ,  := arrow.TimestampFromStringInLocation(, .dtype.Unit, )
		if  != nil {
			return &json.UnmarshalTypeError{
				Value:  ,
				Type:   reflect.TypeOf(arrow.Timestamp(0)),
				Offset: .InputOffset(),
			}
		}
		if  != (.dtype.TimeZone != "") {
			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())
	.UseNumber()
	,  := .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)
)