{{/*
Copyright 2019-present Facebook Inc. All rights reserved.
This source code is licensed under the Apache 2.0 license found
in the LICENSE file in the root directory of this source tree.
*/}}

{{ define "dialect/gremlin/group" }}
{{ $builder := pascal $.Scope.Builder }}
{{ $receiver := receiver $builder }}

func ({{ $receiver }} *{{ $builder }}) gremlinScan(ctx context.Context, v interface{}) error {
	res := &gremlin.Response{}
	query, bindings := {{ $receiver }}.gremlinQuery().Query()
	if err := {{ $receiver }}.driver.Exec(ctx, query, bindings, res); err != nil {
		return err
	}
	if len({{ $receiver }}.fields)+len({{ $receiver }}.fns) == 1 {
		return res.ReadVal(v)
	}
	vm, err := res.ReadValueMap()
	if err != nil {
		return err
	}
	return vm.Decode(v)
}


func ({{ $receiver }} *{{ $builder }}) gremlinQuery() *dsl.Traversal {
	var (
		trs []interface{}
		names []interface{}
	)
	for _, fn := range {{ $receiver }}.fns {
		name, tr := fn.Gremlin("p", "")
		trs = append(trs, tr)
		names = append(names, name)
	}
	for _, f := range {{ $receiver }}.fields {
		names = append(names, f)
		trs = append(trs, __.As("p").Unfold().Values(f).As(f))
	}
	return {{ $receiver }}.gremlin.Group().
				By(__.Values({{ $receiver }}.fields...).Fold()).
				By(__.Fold().Match(trs...).Select(names...)).
				Select(dsl.Values).
				Next()
}
{{ end }}