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

import (
	
	

	
	
	
	
)

// CumulativeOptions controls cumulative operations.
type CumulativeOptions struct {
	// Start is the initial value. A nil value uses the zero value for the
	// input type. A non-nil null scalar is invalid.
	Start scalar.Scalar `compute:"start"`
	// SkipNulls controls whether a null input stops the cumulative operation.
	// Null positions are still null in the output when this is true.
	SkipNulls bool `compute:"skip_nulls"`
}

func (CumulativeOptions) () string { return "CumulativeOptions" }

func ( CumulativeOptions) () {
	if isNilScalar(.Start) {
		return
	}

	if ,  := .Start.(interface{ () });  {
		.()
	}
}

type cumulativeSumState[ arrow.NumericType] struct {
	current         
	skipNulls       bool
	encounteredNull bool
	checked         bool
	add             func(, ) (, error)
}

type ScalarCastFn func(*exec.KernelCtx, scalar.Scalar, arrow.DataType) (scalar.Scalar, error)

func isNilScalar( scalar.Scalar) bool {
	if  == nil {
		return true
	}

	 := reflect.ValueOf()
	return .Kind() == reflect.Ptr && .IsNil()
}

func safeNumericCastScalar( *exec.KernelCtx,  ScalarCastFn,  scalar.Scalar,  arrow.DataType) (scalar.Scalar, error) {
	 := .ID()
	if !arrow.IsInteger() && !arrow.IsFloating() {
		return nil, fmt.Errorf("%w: cumulative sum input type must be numeric, got %s", arrow.ErrType, )
	}
	if arrow.TypeEqual(.DataType(), ) {
		return , nil
	}

	if  == nil {
		return nil, fmt.Errorf("%w: cumulative sum start value caster is not configured", arrow.ErrInvalid)
	}

	,  := (, , )
	if  != nil {
		return nil, fmt.Errorf("%w: cannot cast cumulative sum start value to %s: %v", arrow.ErrInvalid, , )
	}
	return , nil
}

func cumulativeStartValue[ arrow.NumericType]( *exec.KernelCtx,  ScalarCastFn,  scalar.Scalar,  arrow.DataType) (, error) {
	var  
	if isNilScalar() {
		return , nil
	}
	if !.IsValid() {
		return , fmt.Errorf("%w: cumulative sum start value must be valid", arrow.ErrInvalid)
	}

	,  := safeNumericCastScalar(, , , )
	if  != nil {
		return , 
	}
	if ,  := .(scalar.Releasable);  {
		defer .Release()
	}

	,  := .(scalar.PrimitiveScalar)
	if ! {
		return , fmt.Errorf("%w: cumulative sum start value is not primitive", arrow.ErrInvalid)
	}

	 := &exec.ArraySpan{Type: , Len: 1}
	.Buffers[1].Buf = .Data()
	return exec.GetSpanValues[](, 1)[0], nil
}

func initCumulativeSum[ arrow.NumericType]( bool,  ScalarCastFn) exec.KernelInitFn {
	return func( *exec.KernelCtx,  exec.KernelInitArgs) (exec.KernelState, error) {
		 := CumulativeOptions{}
		switch value := .Options.(type) {
		case nil:
		case CumulativeOptions:
			 = 
		case *CumulativeOptions:
			if  != nil {
				 = *
			}
		default:
			return nil, fmt.Errorf("%w: attempted to initialize cumulative sum from invalid function options", arrow.ErrInvalid)
		}

		,  := cumulativeStartValue[](, , .Start, .Inputs[0])
		if  != nil {
			return nil, 
		}

		return &cumulativeSumState[]{
			current:   ,
			skipNulls: .SkipNulls,
			checked:   ,
			add:       checkedAdder[](),
		}, nil
	}
}

func checkedAddSigned[ arrow.IntType](,  ) (, error) {
	if ( > 0 &&  > MaxOf[]()-) || ( < 0 &&  < MinOf[]()-) {
		return 0, errOverflow
	}
	return  + , nil
}

func checkedAddUnsigned[ arrow.UintType](,  ) (, error) {
	if  > MaxOf[]()- {
		return 0, errOverflow
	}
	return  + , nil
}

func checkedAdder[ arrow.NumericType]() func(, ) (, error) {
	var  
	switch any().(type) {
	case int8:
		return func(,  ) (, error) {
			,  := checkedAddSigned(int8(), int8())
			return (), 
		}
	case int16:
		return func(,  ) (, error) {
			,  := checkedAddSigned(int16(), int16())
			return (), 
		}
	case int32:
		return func(,  ) (, error) {
			,  := checkedAddSigned(int32(), int32())
			return (), 
		}
	case int64:
		return func(,  ) (, error) {
			,  := checkedAddSigned(int64(), int64())
			return (), 
		}
	case uint8:
		return func(,  ) (, error) {
			,  := checkedAddUnsigned(uint8(), uint8())
			return (), 
		}
	case uint16:
		return func(,  ) (, error) {
			,  := checkedAddUnsigned(uint16(), uint16())
			return (), 
		}
	case uint32:
		return func(,  ) (, error) {
			,  := checkedAddUnsigned(uint32(), uint32())
			return (), 
		}
	case uint64:
		return func(,  ) (, error) {
			,  := checkedAddUnsigned(uint64(), uint64())
			return (), 
		}
	default:
		return func(,  ) (, error) { return  + , nil }
	}
}

func prepareCumulativeOutput[ arrow.NumericType]( *exec.KernelCtx,  *exec.ExecResult,  bool) {
	if .Len == 0 {
		return
	}

	 := .Allocate(int(.Len) * arrow.GetDataType[]().(arrow.FixedWidthDataType).Bytes())
	.Buffers[1].WrapBuffer()

	if  {
		 := .AllocateBitmap(.Len)
		 := .Bytes()
		for  := range  {
			[] = 0xFF
		}
		.Buffers[0].WrapBuffer()
	}
}

func cumulativeSumNoNulls[ arrow.NumericType]( *cumulativeSumState[],  []*exec.ArraySpan,  []) {
	var  int64
	 := .current
	for ,  := range  {
		 := exec.GetSpanValues[](, 1)
		for  := int64(0);  < .Len; ++ {
			 += []
			[+] = 
		}
		 += .Len
	}
	.current = 
}

func cumulativeSumNoNullsChecked[ arrow.NumericType]( *cumulativeSumState[],  []*exec.ArraySpan,  []) error {
	var  int64
	 := .current
	for ,  := range  {
		 := exec.GetSpanValues[](, 1)
		for  := int64(0);  < .Len; ++ {
			var  error
			,  = .add(, [])
			if  != nil {
				return 
			}
			[+] = 
		}
		 += .Len
	}
	.current = 
	return nil
}

func cumulativeSumWithNulls[ arrow.NumericType]( *cumulativeSumState[],  []*exec.ArraySpan,  [],  []byte) int64 {
	var (
		        int64
		 int64
	)
	 := .current
	for ,  := range  {
		 := exec.GetSpanValues[](, 1)
		for  := int64(0);  < .Len; ++ {
			 := len(.Buffers[0].Buf) == 0 || bitutil.BitIsSet(.Buffers[0].Buf, int(.Offset+))
			 :=  + 
			if ! || .encounteredNull {
				bitutil.ClearBit(, int())
				++
				if ! && !.skipNulls {
					.encounteredNull = true
				}
				continue
			}

			 += []
			[] = 
		}
		 += .Len
	}
	.current = 
	return 
}

func cumulativeSumWithNullsChecked[ arrow.NumericType]( *cumulativeSumState[],  []*exec.ArraySpan,  [],  []byte) (int64, error) {
	var (
		        int64
		 int64
	)
	 := .current
	for ,  := range  {
		 := exec.GetSpanValues[](, 1)
		for  := int64(0);  < .Len; ++ {
			 := len(.Buffers[0].Buf) == 0 || bitutil.BitIsSet(.Buffers[0].Buf, int(.Offset+))
			 :=  + 
			if ! || .encounteredNull {
				bitutil.ClearBit(, int())
				++
				if ! && !.skipNulls {
					.encounteredNull = true
				}
				continue
			}

			var  error
			,  = .add(, [])
			if  != nil {
				return , 
			}
			[] = 
		}
		 += .Len
	}
	.current = 
	return , nil
}

func cumulativeSumSpans[ arrow.NumericType]( *exec.KernelCtx,  *cumulativeSumState[],  []*exec.ArraySpan,  *exec.ExecResult,  bool) error {
	prepareCumulativeOutput[](, , )
	 := exec.GetSpanValues[](, 1)

	if ! && !.encounteredNull {
		if .checked {
			if  := cumulativeSumNoNullsChecked(, , );  != nil {
				.Release()
				return 
			}
		} else {
			cumulativeSumNoNulls(, , )
		}
		return nil
	}

	var (
		 int64
		   error
	)
	if .checked {
		,  = cumulativeSumWithNullsChecked(, , , .Buffers[0].Buf)
	} else {
		 = cumulativeSumWithNulls(, , , .Buffers[0].Buf)
	}
	if  != nil {
		.Release()
		return 
	}
	.Nulls = 
	return nil
}

func cumulativeSumExec[ arrow.NumericType]( *exec.KernelCtx,  *exec.ExecSpan,  *exec.ExecResult) error {
	 := .State.(*cumulativeSumState[])
	 := &.Values[0].Array

	.Len = .Len
	if .Len == 0 {
		return nil
	}

	return cumulativeSumSpans(, , []*exec.ArraySpan{}, , .encounteredNull || .MayHaveNulls())
}

func cumulativeSumExecChunked[ arrow.NumericType]( *exec.KernelCtx,  []*arrow.Chunked,  *exec.ExecResult) ([]*exec.ExecResult, error) {
	 := .State.(*cumulativeSumState[])
	 := [0]
	.Len = int64(.Len())
	if .Len == 0 {
		return []*exec.ExecResult{}, nil
	}

	 := .Chunks()
	 := make([]exec.ArraySpan, len())
	 := make([]*exec.ArraySpan, len())
	 := .encounteredNull || .NullN() != 0
	for ,  := range  {
		[].SetMembers(.Data())
		[] = &[]
		 =  || [].MayHaveNulls()
	}

	if  := cumulativeSumSpans(, , , , );  != nil {
		return nil, 
	}
	return []*exec.ExecResult{}, nil
}

func newCumulativeSumKernel[ arrow.NumericType]( arrow.DataType,  bool,  ScalarCastFn) exec.VectorKernel {
	 := exec.NewVectorKernel(
		[]exec.InputType{exec.NewExactInput()},
		exec.NewOutputType(),
		cumulativeSumExec[],
		initCumulativeSum[](, ))
	.Parallelizable = false
	.CanExecuteChunkWise = false
	.ExecChunked = cumulativeSumExecChunked[]
	return 
}

func cumulativeSumKernels( bool,  ScalarCastFn) []exec.VectorKernel {
	return []exec.VectorKernel{
		newCumulativeSumKernel[int8](arrow.PrimitiveTypes.Int8, , ),
		newCumulativeSumKernel[int16](arrow.PrimitiveTypes.Int16, , ),
		newCumulativeSumKernel[int32](arrow.PrimitiveTypes.Int32, , ),
		newCumulativeSumKernel[int64](arrow.PrimitiveTypes.Int64, , ),
		newCumulativeSumKernel[uint8](arrow.PrimitiveTypes.Uint8, , ),
		newCumulativeSumKernel[uint16](arrow.PrimitiveTypes.Uint16, , ),
		newCumulativeSumKernel[uint32](arrow.PrimitiveTypes.Uint32, , ),
		newCumulativeSumKernel[uint64](arrow.PrimitiveTypes.Uint64, , ),
		newCumulativeSumKernel[float32](arrow.PrimitiveTypes.Float32, , ),
		newCumulativeSumKernel[float64](arrow.PrimitiveTypes.Float64, , ),
	}
}

func ( ScalarCastFn) (,  []exec.VectorKernel) {
	return cumulativeSumKernels(false, ), cumulativeSumKernels(true, )
}