package cypher

import (
	"fmt"

	"git.science.uu.nl/graphpolaris/query-conversion/entity"
)

// checkForQueryCluster will detect (and separate?) if there are multiple queries in the query panel and will try to sepate the queries.
// Maybe also delete floating pills that have no connection (but that is a different function)
func checkForQueryCluster(JSONQuery *entity.IncomingQueryJSON) (*entity.IncomingQueryJSON, *entity.IncomingQueryJSON, bool) {

	// Notes naar moizelf: alle pills die dingen aan elkaar verbinden zijn relations en group bys, filter lijken 'op' een lijntje te leven, maar niet als schakel te dienen
	// Dit zou recursief kunnen: vind een cluster in de json, haal alles uit de json dat verbonden zit aan die cluster, voer de functie opnieuw uit op het restand

	cluster := make(map[string]bool) // aka een set (entities e0 e1 e2, relations r0 .., groub by g0 ..)

	// Dit is het startpunt van de cluster, vrij veel if elses ivm half afgemaakte queries
	// Lots of existance checks

	if len(JSONQuery.Relations) > 0 {
		rel := fmt.Sprintf("r%v", JSONQuery.Relations[0].ID)
		cluster[rel] = true

		if JSONQuery.Relations[0].ToID != -1 {

			// Take the first letter: entities with ID 0 -> e0
			to := fmt.Sprintf("%v%v", string(JSONQuery.Relations[0].ToType[0]), JSONQuery.Relations[0].ToID)
			cluster[to] = true
		}

		if JSONQuery.Relations[0].FromID != -1 {
			from := fmt.Sprintf("%v%v", string(JSONQuery.Relations[0].FromType[0]), JSONQuery.Relations[0].FromID)
			cluster[from] = true
		}

	} else if len(JSONQuery.GroupBys) > 0 {
		gb := fmt.Sprintf("g%v", JSONQuery.GroupBys[0].ID)
		cluster[gb] = true

		// TODO: Wat te doen als de groupby niet goed is aangesloten, want dat crasht ie nogal atm
		group := fmt.Sprintf("%v%v", string(JSONQuery.GroupBys[0].GroupType[0]), JSONQuery.GroupBys[0].GroupID)
		cluster[group] = true

		by := fmt.Sprintf("%v%v", string(JSONQuery.GroupBys[0].ByType[0]), JSONQuery.GroupBys[0].ByID)
		cluster[by] = true

	} else {
		return nil, nil, false
	}
	// Relation toevoegen aan de map
	// Is er geen relation doe dan groupby
	// is die er ook niet dan rip

	for i := 0; i < 100; i++ {
		stop := true

		// kijk langs alle relations en group bys of ie verbonden is aan de cluster en nog niet in de set zit
		// Is dat zo run m opnieuw en kijk of daar weer dingen aan verbonden zijn

		for _, rel := range JSONQuery.Relations {
			// check of de rel er al in zit, dan kan ie geskipped worden
			// zo nee kijk of een van de entities of group by's erin zit, dan is deze dus verbonden

			rela := fmt.Sprintf("r%v", rel.ID)
			if cluster[rela] {
				// If it is already in the cluster then we dont care
				continue
			}

			partOfCluster := false
			// Now comes the check to see if one of its endpoints is in the cluster, meaning everything is in the cluster
			if rel.ToID != -1 {
				to := fmt.Sprintf("%v%v", string(rel.ToType[0]), rel.ToID)

				if cluster[to] {
					partOfCluster = true
				}
			}

			if rel.FromID != -1 {
				from := fmt.Sprintf("%v%v", string(rel.FromType[0]), rel.FromID)

				if cluster[from] {
					partOfCluster = true
				}
			}

			if partOfCluster {
				if rel.ToID != -1 {
					to := fmt.Sprintf("%v%v", string(rel.ToType[0]), rel.ToID)
					cluster[to] = true
				}

				if rel.FromID != -1 {
					from := fmt.Sprintf("%v%v", string(rel.FromType[0]), rel.FromID)
					cluster[from] = true
				}

				cluster[rela] = true
				stop = false
			}
		}

		// Check to see if an entity is connected to the cluster via an 'IN'
		for _, ent := range JSONQuery.Entities {
			self := fmt.Sprintf("e%v", ent.ID)
			if cluster[self] {
				continue
			}

			for _, con := range ent.Constraints {
				if con.InID != -1 {
					in := fmt.Sprintf("%v%v", string(con.InType[0]), con.InID)

					if cluster[in] {
						cluster[self] = true
						stop = false
					}
				}
			}
		}

		// Now the same for Group by's
		for _, gb := range JSONQuery.GroupBys {
			gby := fmt.Sprintf("g%v", gb.ID)

			if cluster[gby] {
				continue
			}

			// It should have been checked that the connections of the group by are valid, since a group by must have all connections filled (in contrary of a relation)

			group := fmt.Sprintf("%v%v", string(gb.GroupType[0]), gb.GroupID)
			by := fmt.Sprintf("%v%v", string(gb.ByType[0]), gb.ByID)

			if cluster[group] || cluster[by] {
				cluster[gby] = true
				cluster[group] = true
				cluster[by] = true
				stop = false
			}

		}

		// ** then for modifiers? although modifiers havent changed yet, since their results must also be used in queries
		// Modifiers will change, so that is a problem for later

		if stop {
			// No new entities were added to the cluster, thus it is finished
			break
		}
	}

	// Now walk through the JSON and divide it into the cluster and rest
	restJSON := entity.IncomingQueryJSON{DatabaseName: JSONQuery.DatabaseName, Limit: JSONQuery.Limit}
	clusterJSON := entity.IncomingQueryJSON{DatabaseName: JSONQuery.DatabaseName, Limit: JSONQuery.Limit}
	isRest := false

	// Loop through entities
	for _, ent := range JSONQuery.Entities {
		name := fmt.Sprintf("e%v", ent.ID)

		if cluster[name] {
			clusterJSON.Entities = append(clusterJSON.Entities, ent)
		} else {
			restJSON.Entities = append(restJSON.Entities, ent)
			isRest = true
		}
	}

	// Loop through relations
	for _, rel := range JSONQuery.Relations {
		name := fmt.Sprintf("r%v", rel.ID)

		if cluster[name] {
			clusterJSON.Relations = append(clusterJSON.Relations, rel)
		} else {
			restJSON.Relations = append(restJSON.Relations, rel)
			isRest = true
		}
	}

	// Loop through groupby's
	for _, gb := range JSONQuery.GroupBys {
		name := fmt.Sprintf("g%v", gb.ID)

		if cluster[name] {
			clusterJSON.GroupBys = append(clusterJSON.GroupBys, gb)
		} else {
			restJSON.GroupBys = append(restJSON.GroupBys, gb)
			isRest = true
		}
	}

	// ** Loop through modifiers

	return &clusterJSON, &restJSON, isRest

	// Nadat cluster is gevonden: maak twee nieuwe jsons aan: cluster en rest
	// Loop door de OG json en voeg alles aan of de cluster of de rest toe
	// Return cluster, rest en een bool die zegt of er een cluster is
	// Wss is het in 99% van de gevallen maar 1 cluster of een cluster met een verdwaalde node, maar toch
}