package database

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/jackc/pgx/v4/pgxpool"
	"log"
	"trikotwaschliste/models"
)

func DbPersons(pool *pgxpool.Pool) gin.H {
	var items []models.PersonListItem
	var persons []models.Person

	// Get items
	witems, err := pool.Query(context.Background(), "SELECT pe.name, count(pe.name)\nFROM washlist wa\nINNER JOIN persons pe ON wa.washed = pe.id\nGROUP BY pe.name\nORDER BY pe.name ASC")
	if err != nil {
		log.Println(err.Error())
	}

	var item models.PersonListItem
	for witems.Next() {
		err = witems.Scan(&item.Name, &item.Count)
		if err != nil {
			log.Println("Items: " + err.Error())
		}
		items = append(items, item)
	}


	// Get full persons list
	wpersons, err := pool.Query(context.Background(), "SELECT id, name FROM persons ORDER BY name ASC")
	if err != nil {
		log.Println(err.Error())
	}

	var person models.Person
	for wpersons.Next() {
		err = wpersons.Scan(&person.Id, &person.Name)
		if err != nil {
			log.Println("Persons: " + err.Error())
		}
		persons = append(persons, person)
	}

	// Merge the list in n^2
	var merge []models.PersonListItem
	merge = append(merge, items...)
	for _, p := range persons {
		found := false
		for _, it := range items {
			if p.Name == it.Name {
				found = true
				break
			}
		}
		if !found {
			merge = append(merge, models.PersonListItem{
				Name:  p.Name,
				Count: 0,
			})
		}
	}

	return gin.H{"items": merge}
}

