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 ?s ?p ?o WHERE { FILTER(false) }"
	}

	bnodeFilter := ""
	if !includeBNodes {
		bnodeFilter = "FILTER(!isBlank(?s) && !isBlank(?o))"
	}

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

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

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

	query := subclassesQuery(selectedNodes, includeBNodes)
	raw, err := q.Query(ctx, query)
	if err != nil {
		logQueryExecutionFailure("subclasses", selectedIDs, includeBNodes, query, err)
		return Result{}, err
	}
	return resultFromTripleBindings(raw, idx, selectedSet, includeBNodes)
}
