package ii

import (
	"strings"

	"git.simanc.com/software/golib/v4/features/mo"
)

func (f *FieldInfo) HasLookup(asName string) (*Lookup, bool) {
	for _, l := range f.Lookup {
		if l.AS == asName && l.From != "" && l.ForeignField != "" {
			return &l, true
		}
	}
	return nil, false
}

func (f *FieldInfo) HasSet(name string) bool {
	for _, s := range f.Set {
		if s.Name == name && s.OP != "" {
			return true
		}
	}
	return false
}

// ArgLookup 将 FieldInfo.Lookup 转化为 mo.Looker 接口
func (f *FieldInfo) ArgLookup(lookup *Lookup) *mo.Looker {
	l := new(mo.Looker)
	l.SetFrom(lookup.From)
	l.SetLocalField(f.Name)
	l.SetForeignField(lookup.ForeignField)
	l.SetAs(lookup.AS)

	pipe := mo.Pipeline{}

	if len(f.Fields) > 0 {
		p := mo.Projects{}
		for _, field := range f.Fields {
			p.AddEnable(field.Name)
		}
		pipe = append(pipe, p.Pipeline())
	}

	if lookup.SUM != "" {
		group := mo.Grouper{}
		group.Add(mo.OID, nil)
		group.Add(lookup.SUM, mo.D{{Key: mo.OptSum, Value: "$" + lookup.SUM}})
		pipe = append(pipe, group.Pipeline())
	}

	if !lookup.List {
		pipe = append(pipe, mo.NewLimiter(1).Pipeline())
	}

	l.SetPipe(pipe)
	return l
}

// ArgSet 为查询结果新增字段
func (f *FieldInfo) ArgSet() *mo.Setter {
	sets := new(mo.Setter)
	for _, set := range f.Set {
		switch set.OP {
		case mo.OptSum:
			sets.SUM(set.Name, strings.Split(set.Value, ","))
		}
	}
	return sets
}
