package db

import (
	"errors"
	"fmt"
	"music-server/pkg/models"
	"os"
	"strings"
)

var compareError = errors.New("no rows in result set")

func ClearSongs(gameId int) {
	if gameId == -1 {
		_, err := Dbpool.Exec(Ctx, "DELETE FROM song")
		if err != nil {
			_, _ = fmt.Fprintf(os.Stderr, "Exec failed: %v\n", err)
		}
	} else {
		_, err := Dbpool.Exec(Ctx, "DELETE FROM song where game_id=$1", gameId)
		if err != nil {
			_, _ = fmt.Fprintf(os.Stderr, "Exec failed: %v\n", err)
		}
	}
}

func AddSong(song models.SongData) {
	_, err := Dbpool.Exec(Ctx,
		"INSERT INTO song(game_id, song_name, path, file_name) VALUES ($1, $2, $3, $4)",
		song.GameId, song.SongName, song.Path, song.FileName)
	if err != nil {
		_, _ = fmt.Fprintf(os.Stderr, "Exec failed: %v\n", err)
	}
}

func CheckSong(songPath string) bool {
	var path string
	err := Dbpool.QueryRow(Ctx,
		"SELECT path FROM song WHERE path = $1", songPath).Scan(&path)
	if err != nil {
		if compareError.Error() != err.Error() {
			_, _ = fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
		}
	}
	return path != ""
}

func UpdateSong(songName string, fileName string, path string) {
	_, err := Dbpool.Exec(Ctx,
		"UPDATE song SET song_name=$1, file_name=$2 WHERE path = $3",
		songName, fileName, path)
	if err != nil {
		_, _ = fmt.Fprintf(os.Stderr, "Exec failed: %v\n", err)
	}
}

func FindSongsFromGame(id int) []models.SongData {
	rows, err := Dbpool.Query(Ctx,
		"SELECT song_name, path, file_name, times_played FROM song WHERE game_id = $1", id)
	if err != nil {
		if compareError.Error() != err.Error() {
			_, _ = fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
		}
		return nil
	}

	var songDataList []models.SongData
	for rows.Next() {
		var songName string
		var path string
		var fileName string
		var timesPlayed int

		err := rows.Scan(&songName, &path, &fileName, &timesPlayed)
		if err != nil {
			if compareError.Error() != err.Error() {
				_, _ = fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
			}
		}

		songDataList = append(songDataList, models.SongData{
			GameId:      id,
			SongName:    songName,
			Path:        path,
			FileName:    fileName,
			TimesPlayed: timesPlayed,
		})
	}
	return songDataList
}

func AddSongPlayed(id int, name string) {
	_, err := Dbpool.Exec(Ctx,
		"UPDATE song SET times_played=times_played+1 WHERE game_id=$1 AND song_name=$2", id, name)
	if err != nil {
		_, _ = fmt.Fprintf(os.Stderr, "Exec failed: %v\n", err)
	}
}

func FetchAllSongs() []models.SongData {
	rows, err := Dbpool.Query(Ctx,
		"SELECT song_name, path FROM song")
	if err != nil {
		if compareError.Error() != err.Error() {
			_, _ = fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
		}
		return nil
	}

	var songDataList []models.SongData
	for rows.Next() {
		var songName string
		var path string

		err := rows.Scan(&songName, &path)
		if err != nil {
			if compareError.Error() != err.Error() {
				_, _ = fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
			}
		}

		songDataList = append(songDataList, models.SongData{
			SongName: songName,
			Path:     path,
		})
	}
	return songDataList
}

func RemoveBrokenSong(song models.SongData) {
	_, err := Dbpool.Exec(Ctx, "DELETE FROM song where path=$1", song.Path)
	if err != nil {
		_, _ = fmt.Fprintf(os.Stderr, "Exec failed: %v\n", err)
	}
}

func RemoveBrokenSongs(songs []models.SongData) {
	joined := ""
	for _, song := range songs {
		joined += "'" + song.Path + "',"
	}
	joined = strings.TrimSuffix(joined, ",")

	_, err := Dbpool.Exec(Ctx, "DELETE FROM song where path in ($1)", joined)
	if err != nil {
		_, _ = fmt.Fprintf(os.Stderr, "Exec failed: %v\n", err)
	}
}
