// 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.

//go:build go1.18

package scalar

import (
	

	
	
	
	
	
	
)

type primitives interface {
	bool | float16.Num | decimal128.Num |
		decimal256.Num | constraints.Integer | constraints.Float |
		arrow.DayTimeInterval | arrow.MonthInterval | arrow.MonthDayNanoInterval
}

type builder[ primitives | []byte] interface {
	AppendNull()
	UnsafeAppend()
	UnsafeAppendBoolToBitmap(bool)
}

type binaryBuilder interface {
	builder[[]byte]
	ReserveData(int)
}

func appendPrimitive[ primitives,  builder[]]( ,  []Scalar) {
	for ,  := range  {
		if .IsValid() {
			.UnsafeAppend(.value().())
		} else {
			.UnsafeAppendBoolToBitmap(false)
		}
	}
}

func appendBinary( binaryBuilder,  []Scalar) {
	var  int
	for ,  := range  {
		 := .(BinaryScalar)
		if .IsValid() {
			 += len(.Data())
		}
	}

	.ReserveData()
	for ,  := range  {
		 := .(BinaryScalar)
		if .IsValid() {
			.UnsafeAppend(.Data())
		} else {
			.AppendNull()
		}
	}
}

type extbuilder interface {
	array.Builder
	StorageBuilder() array.Builder
}

func appendToBldr( array.Builder,  []Scalar) error {
	if len() == 0 {
		return nil
	}

	 := .Type()
	.Reserve(len())
	switch bldr := .(type) {
	case extbuilder:
		 := make([]Scalar, len())
		for ,  := range  {
			[] = .(*Extension).Value
		}

		return (.StorageBuilder(), )
	case *array.BooleanBuilder:
		appendPrimitive(, )
	case *array.Decimal128Builder:
		appendPrimitive(, )
	case *array.Decimal256Builder:
		appendPrimitive(, )
	case *array.FixedSizeBinaryBuilder:
		for ,  := range  {
			 := .(*FixedSizeBinary)
			if .Valid {
				.UnsafeAppend(.Value.Bytes())
			} else {
				.UnsafeAppendBoolToBitmap(false)
			}
		}
	case *array.Int8Builder:
		appendPrimitive(, )
	case *array.Uint8Builder:
		appendPrimitive(, )
	case *array.Int16Builder:
		appendPrimitive(, )
	case *array.Uint16Builder:
		appendPrimitive(, )
	case *array.Int32Builder:
		appendPrimitive(, )
	case *array.Uint32Builder:
		appendPrimitive(, )
	case *array.Int64Builder:
		appendPrimitive(, )
	case *array.Uint64Builder:
		appendPrimitive(, )
	case *array.Float16Builder:
		appendPrimitive(, )
	case *array.Float32Builder:
		appendPrimitive(, )
	case *array.Float64Builder:
		appendPrimitive(, )
	case *array.Date32Builder:
		appendPrimitive(, )
	case *array.Date64Builder:
		appendPrimitive(, )
	case *array.Time32Builder:
		appendPrimitive(, )
	case *array.Time64Builder:
		appendPrimitive(, )
	case *array.DayTimeIntervalBuilder:
		appendPrimitive(, )
	case *array.MonthIntervalBuilder:
		appendPrimitive(, )
	case *array.MonthDayNanoIntervalBuilder:
		appendPrimitive(, )
	case *array.DurationBuilder:
		appendPrimitive(, )
	case *array.TimestampBuilder:
		appendPrimitive(, )
	case array.StringLikeBuilder:
		appendBinary(, )
	case *array.BinaryBuilder:
		appendBinary(, )
	case array.ListLikeBuilder:
		var  int
		for ,  := range  {
			if !.IsValid() {
				continue
			}
			 += .(ListScalar).GetList().Len()
		}
		.ValueBuilder().Reserve()

		for ,  := range  {
			.Append(.IsValid())
			if .IsValid() {
				 := .(ListScalar).GetList()
				for  := 0;  < .Len(); ++ {
					,  := GetScalar(, )
					if  != nil {
						return 
					}
					if  := Append(.ValueBuilder(), );  != nil {
						return 
					}
				}
			}
		}
	case *array.StructBuilder:
		for ,  := range  {
			 := .(*Struct)
			for  := 0;  < .NumField(); ++ {
				if !.Valid || .Value[] == nil {
					.FieldBuilder().UnsafeAppendBoolToBitmap(false)
				} else {
					if  := Append(.FieldBuilder(), .Value[]);  != nil {
						return 
					}
				}
			}
			.UnsafeAppendBoolToBitmap(.Valid)
		}
	case *array.SparseUnionBuilder:
		 := .(*arrow.SparseUnionType)
		for  := 0;  < .NumChildren(); ++ {
			.Child().Reserve(len())
		}

		for ,  := range  {
			// for each scalar
			// 1. append the type code
			// 2. append the value to the corresponding child
			// 3. append null to the other children
			 := .(*SparseUnion)
			.Append(.TypeCode)
			for  := range .Fields() {
				 := .Child()
				if .ChildID ==  {
					if .Valid {
						if  := Append(, .Value[]);  != nil {
							return 
						}
					} else {
						.UnsafeAppendBoolToBitmap(false)
					}
				} else {
					.UnsafeAppendBoolToBitmap(false)
				}
			}
		}
	case *array.DenseUnionBuilder:
		 := .(*arrow.DenseUnionType)
		for  := 0;  < .NumChildren(); ++ {
			.Child().Reserve(len())
		}

		for ,  := range  {
			 := .(*DenseUnion)
			 := .ChildIDs()[.TypeCode]
			.Append(.TypeCode)

			for  := range .Fields() {
				 := .Child()
				if  ==  {
					if .Valid {
						if  := Append(, .Value);  != nil {
							return 
						}
					} else {
						.UnsafeAppendBoolToBitmap(false)
					}
				}
			}
		}
	default:
		return fmt.Errorf("%w: append scalar for type %s", arrow.ErrNotImplemented, )
	}

	return nil
}

// Append requires the passed in builder and scalar to have the same datatype
// otherwise it will return an error. Will return arrow.ErrNotImplemented if
// the type hasn't been implemented for this.
//
// NOTE only available in go1.18+
func ( array.Builder,  Scalar) error {
	return AppendSlice(, []Scalar{})
}

// AppendSlice requires the passed in builder and all scalars in the slice
// to have the same datatype otherwise it will return an error. Will return
// arrow.ErrNotImplemented if the type hasn't been implemented for this.
//
// NOTE only available in go1.18+
func ( array.Builder,  []Scalar) error {
	if len() == 0 {
		return nil
	}

	 := .Type()
	for ,  := range  {
		if !arrow.TypeEqual(, .DataType()) {
			return fmt.Errorf("%w: cannot append scalar of type %s to builder for type %s",
				arrow.ErrInvalid, [0].DataType(), .Type())
		}
	}

	return appendToBldr(, )
}