package database

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

const layoutDE = "02.01.2006"

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

	witems, err := pool.Query(context.Background(), "SELECT wa.id, pe.name, ga.created_at, wa.washed \nFROM washlist wa\nINNER JOIN persons pe ON wa.personid = pe.id\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.Washlist
	for witems.Next() {
		err = witems.Scan(&item.Id, &item.Person, &item.Date, &item.Washed)
		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 UploadName(pool *pgxpool.Pool, id, washID string) bool {
	sID, _ := strconv.Atoi(id)
	if sID <= 0 {
		return false
	}

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

	return true
}
