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

import (
	
	

	
	
	
	
)

var listElementDoc = FunctionDoc{
	Summary: "Compute elements using nested list values and an index",
	Description: "For each list value, return the element at the requested index.\n" +
		"Use an integral scalar for broadcast selection. A one-element array-like\n" +
		"index is accepted only for a matching one-element execution and is not\n" +
		"broadcast over longer input. Supported inputs are List, LargeList,\n" +
		"ListView, LargeListView, and FixedSizeList; Map is not supported.\n" +
		"Null lists and null child values produce null results. A null or negative\n" +
		"index is invalid, as is an index outside any non-null list's length\n" +
		"(including an empty list). StringView, BinaryView, and dictionary-backed\n" +
		"extension children are not supported, including when nested inside\n" +
		"another child type.",
	ArgNames: []string{"lists", "index"},
}

func validateListElementIndex( Datum) error {
	switch .Kind() {
	case KindScalar:
		,  := .(*ScalarDatum)
		if ! || .Value == nil {
			return fmt.Errorf("%w: list_element requires a scalar index datum", arrow.ErrType)
		}
		return kernels.ValidateListElementScalarIndex(.Value)
	case KindArray, KindChunked:
		if .Len() == 0 {
			return fmt.Errorf("%w: list_element index array is empty", arrow.ErrInvalid)
		}
		if .Len() > 1 {
			return fmt.Errorf("%w: list_element does not support arrays of list indices", arrow.ErrNotImplemented)
		}
	}
	return nil
}

func validateListElementOutputType( Datum) error {
	var  arrow.DataType
	switch .Kind() {
	case KindScalar:
		,  := .(*ScalarDatum)
		if ! || .Value == nil {
			return nil
		}
		 = .Value.DataType()
	case KindArray, KindChunked:
		,  := .(ArrayLikeDatum)
		if ! {
			return nil
		}
		 = .Type()
	default:
		return nil
	}

	,  := .(arrow.ListLikeType)
	if ! || kernels.ListElementOutputTypeSupported(.Elem()) {
		return nil
	}
	return fmt.Errorf("%w: list_element output type %s is not supported", arrow.ErrNotImplemented, .Elem())
}

type listElementFunction struct {
	ScalarFunction
}

func listElementScalarResultSupported( arrow.DataType,  bool) bool {
	switch .ID() {
	case arrow.BINARY_VIEW, arrow.STRING_VIEW, arrow.LIST_VIEW, arrow.LARGE_LIST_VIEW:
		return false
	case arrow.EXTENSION:
		return (.(arrow.ExtensionType).StorageType(), )
	case arrow.STRUCT:
		for ,  := range .(*arrow.StructType).Fields() {
			if !(.Type, ) {
				return false
			}
		}
	case arrow.SPARSE_UNION:
		if .(arrow.UnionType).NumFields() == 0 {
			return false
		}
		for ,  := range .(arrow.UnionType).Fields() {
			if !(.Type, ) {
				return false
			}
		}
	case arrow.DENSE_UNION:
		if ! {
			return true
		}
		 := .(arrow.UnionType).Fields()
		return len() != 0 && ([0].Type, true)
	case arrow.RUN_END_ENCODED:
		return (.(*arrow.RunEndEncodedType).Encoded(), )
	}
	return true
}

func listElementScalarArrayValueSupported( arrow.Array,  int) bool {
	if .IsNull() {
		return listElementScalarResultSupported(.DataType(), true)
	}

	switch values := .(type) {
	case *array.BinaryView, *array.StringView, *array.ListView, *array.LargeListView:
		return false
	case array.ExtensionArray:
		return (.Storage(), )
	case *array.Struct:
		for  := 0;  < .NumField(); ++ {
			if !(.Field(), ) {
				return false
			}
		}
	case *array.SparseUnion:
		for  := 0;  < .NumFields(); ++ {
			if !(.Field(), ) {
				return false
			}
		}
	case *array.DenseUnion:
		 := .Field(.ChildID())
		if  == nil {
			return false
		}
		 := .ValueOffset()
		if  < 0 || int64() >= int64(.Len()) {
			return false
		}
		return (, int())
	case *array.RunEndEncoded:
		return (.Values(), .GetPhysicalIndex())
	}
	return true
}

// Validate the index before scalar execution splits arguments into spans. The
// index contract is defined by the original Datum, not by the length of an
// execution span.
func ( *listElementFunction) ( context.Context,  FunctionOptions,  ...Datum) (Datum, error) {
	if  := .checkArity(len());  != nil {
		return nil, 
	}
	if  := checkOptions(, );  != nil {
		return nil, 
	}

	if  := validateListElementIndex([1]);  != nil {
		return nil, 
	}
	if  := validateListElementOutputType([0]);  != nil {
		return nil, 
	}
	if [0].Kind() == KindScalar && [1].Kind() == KindScalar {
		,  := [1].(*ScalarDatum)
		if ! {
			return nil, fmt.Errorf("%w: list_element requires a scalar index datum", arrow.ErrType)
		}
		,  := [0].(*ScalarDatum)
		if ! {
			return nil, fmt.Errorf("%w: list_element requires a list-like input", arrow.ErrType)
		}
		if .Value == nil {
			return nil, fmt.Errorf("%w: list_element requires a list-like scalar input", arrow.ErrType)
		}

		,  := .Type().(arrow.ListLikeType)
		if ! {
			return nil, fmt.Errorf("%w: list_element requires a list-like input", arrow.ErrType)
		}
		,  := .Value.(scalar.ListScalar)
		if ! {
			return nil, fmt.Errorf("%w: list_element requires a list-like scalar input", arrow.ErrType)
		}
		if !listElementScalarResultSupported(.Elem(), !.IsValid()) {
			return nil, fmt.Errorf("%w: list_element scalar output type %s is not supported", arrow.ErrNotImplemented, .Elem())
		}
		if !.IsValid() {
			if ,  := .DispatchExact(.Type(), .Type());  != nil {
				return nil, 
			}
			if  := context.Cause();  != nil {
				return nil, 
			}
			// Null scalar construction does not need array concatenation or
			// unboxing, which do not support every nested scalar type.
			return &ScalarDatum{Value: scalar.MakeNullScalar(.Elem())}, nil
		}
		if .GetList() != nil {
			,  := kernels.ListElementScalarIndex(.Value)
			if  != nil {
				return nil, 
			}
			 := .GetList()
			if  < uint64(.Len()) {
				if !listElementScalarArrayValueSupported(, int()) {
					return nil, fmt.Errorf("%w: list_element scalar output value %s is not supported", arrow.ErrNotImplemented, .DataType())
				}
				if .IsNull(int()) {
					if ,  := .DispatchExact(.Type(), .Type());  != nil {
						return nil, 
					}
					if  := context.Cause();  != nil {
						return nil, 
					}
					,  := scalar.GetScalar(, int())
					if  != nil {
						return nil, 
					}
					return &ScalarDatum{Value: }, nil
				}
			}
		}
	}

	return .ScalarFunction.Execute(, , ...)
}

func ( FunctionRegistry) {
	 := &listElementFunction{ScalarFunction: *NewScalarFunction("list_element", Binary(), listElementDoc)}
	for ,  := range kernels.GetListElementKernels() {
		if  := .AddKernel();  != nil {
			panic()
		}
	}

	.AddFunction(, false)
}

func ( context.Context, ,  Datum) (Datum, error) {
	return CallFunction(, "list_element", nil, , )
}