package selection_queries

import (
	"context"
	"fmt"
	"strings"
)

func subclassesQuery(selectedNodes []NodeRef, includeBNodes bool) string {
	valuesTerms := make([]string, 0, len(selectedNodes))
	for _, n := range selectedNodes {
		t := valuesTerm(n)
		if t == "" {
			continue
		}
		valuesTerms = append(valuesTerms, t)
	}

	if len(valuesTerms) == 0 {
		return "SELECT ?nbr WHERE { FILTER(false) }"
	}

	bnodeFilter := ""
	if !includeBNodes {
		bnodeFilter = "FILTER(!isBlank(?nbr))"
	}

	values := strings.Join(valuesTerms, " ")
	return fmt.Sprintf(`
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>

SELECT DISTINCT ?nbr
WHERE {
  VALUES ?sel { %s }
  ?nbr rdfs:subClassOf ?sel .
  FILTER(!isLiteral(?nbr))
  FILTER(?nbr != ?sel)
  %s
}
`, values, bnodeFilter)
}

func runSubclasses(ctx context.Context, q Querier, idx Index, selectedIDs []uint32, includeBNodes bool) ([]uint32, error) {
	selectedNodes, selectedSet := selectedNodesFromIDs(idx, selectedIDs, includeBNodes)
	if len(selectedNodes) == 0 {
		return []uint32{}, nil
	}

	raw, err := q.Query(ctx, subclassesQuery(selectedNodes, includeBNodes))
	if err != nil {
		return nil, err
	}
	return idsFromBindings(raw, "nbr", idx, selectedSet, includeBNodes)
}
