// Copyright (c) 2024-2026 Celestino Amoroso (celestino.amoroso@gmail.com).
// All rights reserved.

// operator-length.go
package expr

import (
	"git.portale-stac.it/go-pkg/expr/kern"
	"git.portale-stac.it/go-pkg/expr/scan"
)

//-------- length term

func newLengthTerm(tk *scan.Token) (inst *scan.Term) {
	return &scan.Term{
		Tk:       *tk,
		Children: make([]*scan.Term, 0, 1),
		Position: scan.PosPrefix,
		Priority: scan.PriSign,
		EvalFunc: evalLength,
	}
}

func evalLength(ctx kern.ExprContext, opTerm *scan.Term) (v any, err error) {
	var childValue any

	if childValue, err = opTerm.EvalPrefix(ctx); err != nil {
		return
	}

	if kern.IsList(childValue) {
		ls, _ := childValue.(*kern.ListType)
		v = int64(len(*ls))
	} else if kern.IsString(childValue) {
		s, _ := childValue.(string)
		v = int64(len(s))
	} else if kern.IsDict(childValue) {
		m, _ := childValue.(*kern.DictType)
		v = int64(len(*m))
	} else if it, ok := childValue.(kern.Iterator); ok {
		v = int64(it.Count())
		// if extIt, ok := childValue.(ExtIterator); ok && extIt.HasOperation(CountName) {
		// 	count, _ := extIt.CallOperation(CountName, nil)
		// 	v, _ = ToGoInt(count, "")
		// } else {
		// 	v = int64(it.Index() + 1)
		// }
	} else {
		err = opTerm.ErrIncompatiblePrefixPostfixType(childValue)
	}
	return
}

// init
func init() {
	scan.RegisterTermConstructor(scan.SymHash, newLengthTerm)
}
