package database

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

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

	witems, err := pool.Query(context.Background(), "SELECT wa.id, wa.personid, ga.created_at\nFROM washlist wa\nINNER JOIN gamedata ga ON wa.gamedataid = ga.id ORDER BY ga.created_at ASC")
	if err != nil {
		log.Println(err.Error())
	}

	var item models.WashlistAdmin
	for witems.Next() {
		err = witems.Scan(&item.Id, &item.PersonId, &item.Date)
		if err != nil {
			log.Println(err.Error())
		}
		item.DateString = item.Date.Format(layoutDE)
		items = append(items, item)
	}

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

	persons = append(persons, models.Person{
		Id:   -1,
		Name: "-- Auswählen --",
	})
	var person models.Person
	for wperson.Next() {
		err = wperson.Scan(&person.Id, &person.Name)
		if err != nil {
			log.Println(err.Error())
		}
		persons = append(persons, person)
	}


	return gin.H{"items": items, "persons": persons}
}

func ChangeName(pool *pgxpool.Pool, id, personID string) bool {
	sID, _ := strconv.Atoi(id)
	if sID <= 0 {
		return false
	}

	pool.Exec(context.Background(), "UPDATE washlist SET personid = $1 WHERE id = $2", id, personID)

	return true
}

func Logs(queue *logbuffer.Queue) gin.H {
	return gin.H{"items": queue.ToSlice()}
}