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

// operator-selector.go
package expr

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

//-------- selector term

func newSelectorTerm(tk *scan.Token) (inst *scan.Term) {
	return &scan.Term{
		Tk:       *tk,
		Children: make([]*scan.Term, 0, 3),
		Position: scan.PosInfix,
		Priority: scan.PriSelector,
		EvalFunc: evalSelector,
	}
}

func trySelectorCase(ctx kern.ExprContext, exprValue, caseSel any, caseIndex int) (match bool, selectedValue any, err error) {
	caseData, _ := caseSel.(*selectorCase)
	if caseData.filterList == nil {
		selectedValue, err = caseData.caseExpr.Eval(ctx)
		match = true
	} else if filterList, ok := caseData.filterList.Value().([]*scan.Term); ok {
		if len(filterList) == 0 {
			var valueAsInt = int64(0)
			if b, ok := exprValue.(bool); ok {
				if !b {
					valueAsInt = 1
				}
			} else if valueAsInt, ok = exprValue.(int64); !ok {
				return
			}
			if valueAsInt == int64(caseIndex) {
				selectedValue, err = caseData.caseExpr.Eval(ctx)
				match = true
			}
		} else {
			var caseValue any
			for _, caseTerm := range filterList {
				if caseValue, err = caseTerm.Compute(ctx); err != nil || caseValue == exprValue {
					selectedValue, err = caseData.caseExpr.Eval(ctx)
					match = true
					break
				}
			}
		}
	}
	return
}

func evalSelector(ctx kern.ExprContext, opTerm *scan.Term) (v any, err error) {
	var exprValue any
	var match bool

	if err = opTerm.CheckOperands(); err != nil {
		return
	}
	exprTerm := opTerm.Children[0]
	if exprValue, err = exprTerm.Compute(ctx); err != nil {
		return
	}

	caseListTerm := opTerm.Children[1]
	caseList, _ := caseListTerm.Value().([]*scan.Term)
	for i, caseTerm := range caseList {
		caseSel := caseTerm.Value()
		if match, v, err = trySelectorCase(ctx, exprValue, caseSel, i); err != nil || match {
			break
		}
	}
	if err == nil && !match {
		err = exprTerm.Tk.Errorf("no case catches the value (%v) of the selection expression", exprValue)
	}
	return
}

// init
func init() {
	scan.RegisterTermConstructor(sym.SymSelector, newSelectorTerm)
}
