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

// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"fmt"
	"math"

	"entgo.io/ent/dialect/gremlin"
	"entgo.io/ent/dialect/gremlin/graph/dsl"
	"entgo.io/ent/dialect/gremlin/graph/dsl/__"
	"entgo.io/ent/dialect/gremlin/graph/dsl/g"
	"entgo.io/ent/entc/integration/gremlin/ent/exvaluescan"
	"entgo.io/ent/entc/integration/gremlin/ent/predicate"
)

// ExValueScanQuery is the builder for querying ExValueScan entities.
type ExValueScanQuery struct {
	config
	ctx        *QueryContext
	order      []exvaluescan.Order
	inters     []Interceptor
	predicates []predicate.ExValueScan
	// intermediate query (i.e. traversal path).
	gremlin *dsl.Traversal
	path    func(context.Context) (*dsl.Traversal, error)
}

// Where adds a new predicate for the ExValueScanQuery builder.
func (evsq *ExValueScanQuery) Where(ps ...predicate.ExValueScan) *ExValueScanQuery {
	evsq.predicates = append(evsq.predicates, ps...)
	return evsq
}

// Limit the number of records to be returned by this query.
func (evsq *ExValueScanQuery) Limit(limit int) *ExValueScanQuery {
	evsq.ctx.Limit = &limit
	return evsq
}

// Offset to start from.
func (evsq *ExValueScanQuery) Offset(offset int) *ExValueScanQuery {
	evsq.ctx.Offset = &offset
	return evsq
}

// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (evsq *ExValueScanQuery) Unique(unique bool) *ExValueScanQuery {
	evsq.ctx.Unique = &unique
	return evsq
}

// Order specifies how the records should be ordered.
func (evsq *ExValueScanQuery) Order(o ...exvaluescan.Order) *ExValueScanQuery {
	evsq.order = append(evsq.order, o...)
	return evsq
}

// First returns the first ExValueScan entity from the query.
// Returns a *NotFoundError when no ExValueScan was found.
func (evsq *ExValueScanQuery) First(ctx context.Context) (*ExValueScan, error) {
	nodes, err := evsq.Limit(1).All(setContextOp(ctx, evsq.ctx, "First"))
	if err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nil, &NotFoundError{exvaluescan.Label}
	}
	return nodes[0], nil
}

// FirstX is like First, but panics if an error occurs.
func (evsq *ExValueScanQuery) FirstX(ctx context.Context) *ExValueScan {
	node, err := evsq.First(ctx)
	if err != nil && !IsNotFound(err) {
		panic(err)
	}
	return node
}

// FirstID returns the first ExValueScan ID from the query.
// Returns a *NotFoundError when no ExValueScan ID was found.
func (evsq *ExValueScanQuery) FirstID(ctx context.Context) (id string, err error) {
	var ids []string
	if ids, err = evsq.Limit(1).IDs(setContextOp(ctx, evsq.ctx, "FirstID")); err != nil {
		return
	}
	if len(ids) == 0 {
		err = &NotFoundError{exvaluescan.Label}
		return
	}
	return ids[0], nil
}

// FirstIDX is like FirstID, but panics if an error occurs.
func (evsq *ExValueScanQuery) FirstIDX(ctx context.Context) string {
	id, err := evsq.FirstID(ctx)
	if err != nil && !IsNotFound(err) {
		panic(err)
	}
	return id
}

// Only returns a single ExValueScan entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one ExValueScan entity is found.
// Returns a *NotFoundError when no ExValueScan entities are found.
func (evsq *ExValueScanQuery) Only(ctx context.Context) (*ExValueScan, error) {
	nodes, err := evsq.Limit(2).All(setContextOp(ctx, evsq.ctx, "Only"))
	if err != nil {
		return nil, err
	}
	switch len(nodes) {
	case 1:
		return nodes[0], nil
	case 0:
		return nil, &NotFoundError{exvaluescan.Label}
	default:
		return nil, &NotSingularError{exvaluescan.Label}
	}
}

// OnlyX is like Only, but panics if an error occurs.
func (evsq *ExValueScanQuery) OnlyX(ctx context.Context) *ExValueScan {
	node, err := evsq.Only(ctx)
	if err != nil {
		panic(err)
	}
	return node
}

// OnlyID is like Only, but returns the only ExValueScan ID in the query.
// Returns a *NotSingularError when more than one ExValueScan ID is found.
// Returns a *NotFoundError when no entities are found.
func (evsq *ExValueScanQuery) OnlyID(ctx context.Context) (id string, err error) {
	var ids []string
	if ids, err = evsq.Limit(2).IDs(setContextOp(ctx, evsq.ctx, "OnlyID")); err != nil {
		return
	}
	switch len(ids) {
	case 1:
		id = ids[0]
	case 0:
		err = &NotFoundError{exvaluescan.Label}
	default:
		err = &NotSingularError{exvaluescan.Label}
	}
	return
}

// OnlyIDX is like OnlyID, but panics if an error occurs.
func (evsq *ExValueScanQuery) OnlyIDX(ctx context.Context) string {
	id, err := evsq.OnlyID(ctx)
	if err != nil {
		panic(err)
	}
	return id
}

// All executes the query and returns a list of ExValueScans.
func (evsq *ExValueScanQuery) All(ctx context.Context) ([]*ExValueScan, error) {
	ctx = setContextOp(ctx, evsq.ctx, "All")
	if err := evsq.prepareQuery(ctx); err != nil {
		return nil, err
	}
	qr := querierAll[[]*ExValueScan, *ExValueScanQuery]()
	return withInterceptors[[]*ExValueScan](ctx, evsq, qr, evsq.inters)
}

// AllX is like All, but panics if an error occurs.
func (evsq *ExValueScanQuery) AllX(ctx context.Context) []*ExValueScan {
	nodes, err := evsq.All(ctx)
	if err != nil {
		panic(err)
	}
	return nodes
}

// IDs executes the query and returns a list of ExValueScan IDs.
func (evsq *ExValueScanQuery) IDs(ctx context.Context) (ids []string, err error) {
	if evsq.ctx.Unique == nil && evsq.path != nil {
		evsq.Unique(true)
	}
	ctx = setContextOp(ctx, evsq.ctx, "IDs")
	if err = evsq.Select(exvaluescan.FieldID).Scan(ctx, &ids); err != nil {
		return nil, err
	}
	return ids, nil
}

// IDsX is like IDs, but panics if an error occurs.
func (evsq *ExValueScanQuery) IDsX(ctx context.Context) []string {
	ids, err := evsq.IDs(ctx)
	if err != nil {
		panic(err)
	}
	return ids
}

// Count returns the count of the given query.
func (evsq *ExValueScanQuery) Count(ctx context.Context) (int, error) {
	ctx = setContextOp(ctx, evsq.ctx, "Count")
	if err := evsq.prepareQuery(ctx); err != nil {
		return 0, err
	}
	return withInterceptors[int](ctx, evsq, querierCount[*ExValueScanQuery](), evsq.inters)
}

// CountX is like Count, but panics if an error occurs.
func (evsq *ExValueScanQuery) CountX(ctx context.Context) int {
	count, err := evsq.Count(ctx)
	if err != nil {
		panic(err)
	}
	return count
}

// Exist returns true if the query has elements in the graph.
func (evsq *ExValueScanQuery) Exist(ctx context.Context) (bool, error) {
	ctx = setContextOp(ctx, evsq.ctx, "Exist")
	switch _, err := evsq.FirstID(ctx); {
	case IsNotFound(err):
		return false, nil
	case err != nil:
		return false, fmt.Errorf("ent: check existence: %w", err)
	default:
		return true, nil
	}
}

// ExistX is like Exist, but panics if an error occurs.
func (evsq *ExValueScanQuery) ExistX(ctx context.Context) bool {
	exist, err := evsq.Exist(ctx)
	if err != nil {
		panic(err)
	}
	return exist
}

// Clone returns a duplicate of the ExValueScanQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (evsq *ExValueScanQuery) Clone() *ExValueScanQuery {
	if evsq == nil {
		return nil
	}
	return &ExValueScanQuery{
		config:     evsq.config,
		ctx:        evsq.ctx.Clone(),
		order:      append([]exvaluescan.Order{}, evsq.order...),
		inters:     append([]Interceptor{}, evsq.inters...),
		predicates: append([]predicate.ExValueScan{}, evsq.predicates...),
		// clone intermediate query.
		gremlin: evsq.gremlin.Clone(),
		path:    evsq.path,
	}
}

// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
//	var v []struct {
//		Binary *url.URL `json:"binary,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.ExValueScan.Query().
//		GroupBy(exvaluescan.FieldBinary).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (evsq *ExValueScanQuery) GroupBy(field string, fields ...string) *ExValueScanGroupBy {
	evsq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &ExValueScanGroupBy{build: evsq}
	grbuild.flds = &evsq.ctx.Fields
	grbuild.label = exvaluescan.Label
	grbuild.scan = grbuild.Scan
	return grbuild
}

// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
//	var v []struct {
//		Binary *url.URL `json:"binary,omitempty"`
//	}
//
//	client.ExValueScan.Query().
//		Select(exvaluescan.FieldBinary).
//		Scan(ctx, &v)
func (evsq *ExValueScanQuery) Select(fields ...string) *ExValueScanSelect {
	evsq.ctx.Fields = append(evsq.ctx.Fields, fields...)
	sbuild := &ExValueScanSelect{ExValueScanQuery: evsq}
	sbuild.label = exvaluescan.Label
	sbuild.flds, sbuild.scan = &evsq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a ExValueScanSelect configured with the given aggregations.
func (evsq *ExValueScanQuery) Aggregate(fns ...AggregateFunc) *ExValueScanSelect {
	return evsq.Select().Aggregate(fns...)
}

func (evsq *ExValueScanQuery) prepareQuery(ctx context.Context) error {
	for _, inter := range evsq.inters {
		if inter == nil {
			return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
		}
		if trv, ok := inter.(Traverser); ok {
			if err := trv.Traverse(ctx, evsq); err != nil {
				return err
			}
		}
	}
	if evsq.path != nil {
		prev, err := evsq.path(ctx)
		if err != nil {
			return err
		}
		evsq.gremlin = prev
	}
	return nil
}

func (evsq *ExValueScanQuery) gremlinAll(ctx context.Context, hooks ...queryHook) ([]*ExValueScan, error) {
	res := &gremlin.Response{}
	traversal := evsq.gremlinQuery(ctx)
	if len(evsq.ctx.Fields) > 0 {
		fields := make([]any, len(evsq.ctx.Fields))
		for i, f := range evsq.ctx.Fields {
			fields[i] = f
		}
		traversal.ValueMap(fields...)
	} else {
		traversal.ValueMap(true)
	}
	query, bindings := traversal.Query()
	if err := evsq.driver.Exec(ctx, query, bindings, res); err != nil {
		return nil, err
	}
	var evsSlice ExValueScans
	if err := evsSlice.FromResponse(res); err != nil {
		return nil, err
	}
	for i := range evsSlice {
		evsSlice[i].config = evsq.config
	}
	return evsSlice, nil
}

func (evsq *ExValueScanQuery) gremlinCount(ctx context.Context) (int, error) {
	res := &gremlin.Response{}
	query, bindings := evsq.gremlinQuery(ctx).Count().Query()
	if err := evsq.driver.Exec(ctx, query, bindings, res); err != nil {
		return 0, err
	}
	return res.ReadInt()
}

func (evsq *ExValueScanQuery) gremlinQuery(context.Context) *dsl.Traversal {
	v := g.V().HasLabel(exvaluescan.Label)
	if evsq.gremlin != nil {
		v = evsq.gremlin.Clone()
	}
	for _, p := range evsq.predicates {
		p(v)
	}
	if len(evsq.order) > 0 {
		v.Order()
		for _, p := range evsq.order {
			p(v)
		}
	}
	switch limit, offset := evsq.ctx.Limit, evsq.ctx.Offset; {
	case limit != nil && offset != nil:
		v.Range(*offset, *offset+*limit)
	case offset != nil:
		v.Range(*offset, math.MaxInt32)
	case limit != nil:
		v.Limit(*limit)
	}
	if unique := evsq.ctx.Unique; unique == nil || *unique {
		v.Dedup()
	}
	return v
}

// ExValueScanGroupBy is the group-by builder for ExValueScan entities.
type ExValueScanGroupBy struct {
	selector
	build *ExValueScanQuery
}

// Aggregate adds the given aggregation functions to the group-by query.
func (evsgb *ExValueScanGroupBy) Aggregate(fns ...AggregateFunc) *ExValueScanGroupBy {
	evsgb.fns = append(evsgb.fns, fns...)
	return evsgb
}

// Scan applies the selector query and scans the result into the given value.
func (evsgb *ExValueScanGroupBy) Scan(ctx context.Context, v any) error {
	ctx = setContextOp(ctx, evsgb.build.ctx, "GroupBy")
	if err := evsgb.build.prepareQuery(ctx); err != nil {
		return err
	}
	return scanWithInterceptors[*ExValueScanQuery, *ExValueScanGroupBy](ctx, evsgb.build, evsgb, evsgb.build.inters, v)
}

func (evsgb *ExValueScanGroupBy) gremlinScan(ctx context.Context, root *ExValueScanQuery, v any) error {
	var (
		trs   []any
		names []any
	)
	for _, fn := range evsgb.fns {
		name, tr := fn("p", "")
		trs = append(trs, tr)
		names = append(names, name)
	}
	for _, f := range *evsgb.flds {
		names = append(names, f)
		trs = append(trs, __.As("p").Unfold().Values(f).As(f))
	}
	query, bindings := root.gremlinQuery(ctx).Group().
		By(__.Values(*evsgb.flds...).Fold()).
		By(__.Fold().Match(trs...).Select(names...)).
		Select(dsl.Values).
		Next().
		Query()
	res := &gremlin.Response{}
	if err := evsgb.build.driver.Exec(ctx, query, bindings, res); err != nil {
		return err
	}
	if len(*evsgb.flds)+len(evsgb.fns) == 1 {
		return res.ReadVal(v)
	}
	vm, err := res.ReadValueMap()
	if err != nil {
		return err
	}
	return vm.Decode(v)
}

// ExValueScanSelect is the builder for selecting fields of ExValueScan entities.
type ExValueScanSelect struct {
	*ExValueScanQuery
	selector
}

// Aggregate adds the given aggregation functions to the selector query.
func (evss *ExValueScanSelect) Aggregate(fns ...AggregateFunc) *ExValueScanSelect {
	evss.fns = append(evss.fns, fns...)
	return evss
}

// Scan applies the selector query and scans the result into the given value.
func (evss *ExValueScanSelect) Scan(ctx context.Context, v any) error {
	ctx = setContextOp(ctx, evss.ctx, "Select")
	if err := evss.prepareQuery(ctx); err != nil {
		return err
	}
	return scanWithInterceptors[*ExValueScanQuery, *ExValueScanSelect](ctx, evss.ExValueScanQuery, evss, evss.inters, v)
}

func (evss *ExValueScanSelect) gremlinScan(ctx context.Context, root *ExValueScanQuery, v any) error {
	var (
		res       = &gremlin.Response{}
		traversal = root.gremlinQuery(ctx)
	)
	if fields := evss.ctx.Fields; len(fields) == 1 {
		if fields[0] != exvaluescan.FieldID {
			traversal = traversal.Values(fields...)
		} else {
			traversal = traversal.ID()
		}
	} else {
		fields := make([]any, len(evss.ctx.Fields))
		for i, f := range evss.ctx.Fields {
			fields[i] = f
		}
		traversal = traversal.ValueMap(fields...)
	}
	query, bindings := traversal.Query()
	if err := evss.driver.Exec(ctx, query, bindings, res); err != nil {
		return err
	}
	if len(root.ctx.Fields) == 1 {
		return res.ReadVal(v)
	}
	vm, err := res.ReadValueMap()
	if err != nil {
		return err
	}
	return vm.Decode(v)
}
