package database

import (
	"fmt"
	"music-server/internal/db"
	"os"
	"time"
)

type gameData struct {
	Id            int
	GameName      string
	Added         time.Time
	Deleted       time.Time
	LastChanged   time.Time
	Path          string
	TimesPlayed   int
	LastPlayed    time.Time
	NumberOfSongs int32
}

func GetGameName(gameId int) string {
	var gameName = ""
	err := db.Dbpool.QueryRow(db.Ctx,
		"SELECT game_name FROM game WHERE id = $1", gameId).Scan(&gameName)
	if err != nil {
		if compareError.Error() != err.Error() {
			_, _ = fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
		}
		return ""
	}
	return gameName
}

func SetGameDeletionDate() {
	_, err := db.Dbpool.Exec(db.Ctx,
		"UPDATE game SET deleted=$1 WHERE deleted IS NULL", time.Now())
	if err != nil {
		_, _ = fmt.Fprintf(os.Stderr, "Exec failed: %v\n", err)
	}
}

func UpdateGameName(id int, name string, path string) {
	_, err := db.Dbpool.Exec(db.Ctx,
		"UPDATE game SET game_name=$1, path=$2, last_changed=$3 WHERE id=$4",
		name, path, time.Now(), id)
	if err != nil {
		_, _ = fmt.Fprintf(os.Stderr, "Exec failed: %v\n", err)
	}
}

func RemoveDeletionDate(id int) {
	_, err := db.Dbpool.Exec(db.Ctx,
		"UPDATE game SET deleted=null WHERE id=$1", id)
	if err != nil {
		_, _ = fmt.Fprintf(os.Stderr, "Exec failed: %v\n", err)
	}
}

func GetIdByGameName(name string) int {
	var gameId = -1
	err := db.Dbpool.QueryRow(db.Ctx,
		"SELECT id FROM game WHERE game_name = $1", name).Scan(&gameId)
	if err != nil {
		if compareError.Error() != err.Error() {
			_, _ = fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
		}
		return -1
	}
	return gameId
}

func InsertGame(name string, path string) int {
	gameId := -1
	err := db.Dbpool.QueryRow(db.Ctx,
		"INSERT INTO game(game_name, path, added) VALUES ($1, $2, $3) RETURNING id",
		name, path, time.Now()).Scan(&gameId)
	if err != nil {
		if compareError.Error() != err.Error() {
			_, _ = fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
		}
		db.ResetGameIdSeq()
		err2 := db.Dbpool.QueryRow(db.Ctx,
			"INSERT INTO game(game_name, path, added) VALUES ($1, $2, $3) RETURNING id",
			name, path, time.Now()).Scan(&gameId)
		if err2 != nil {
			if compareError.Error() != err2.Error() {
				_, _ = fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
			}
			return -1
		}
	}
	return gameId
}

func InsertGameWithExistingId(id int, name string, path string) {
	_, err := db.Dbpool.Exec(db.Ctx,
		"INSERT INTO game(id, game_name, path, added) VALUES ($1, $2, $3, $4)",
		id, name, path, time.Now())
	if err != nil {
		_, _ = fmt.Fprintf(os.Stderr, "Exec failed: %v\n", err)
	}
}
