package services

import (
	"encoding/json"
	"github.com/bwmarrin/discordgo"
	"os"
)

type Server struct {
	Name     string               `json:"name"`
	GuildID  string               `json:"GuildID"`
	Webhooks []*discordgo.Webhook `json:"Webhooks"`
}

var ServerList []Server

func InitServers() {
	ServerList = readJson()
}

func AddServer(GuildID string, s *discordgo.Session) Server {
	ServerList = readJson()
	preview, err := s.GuildPreview(GuildID)
	if err != nil {
	}
	Webhooks, _ := s.GuildWebhooks(GuildID)

	server := Server{
		Name:     preview.Name,
		GuildID:  GuildID,
		Webhooks: Webhooks,
	}
	var exists bool

	for i, oldServer := range ServerList {
		if oldServer.GuildID == server.GuildID {
			ServerList[i] = server
			exists = true
			break
		}
	}
	if !exists {
		ServerList = append(ServerList, server)
	}

	rankingsJson, _ := json.Marshal(ServerList)
	err = os.WriteFile("servers.json", rankingsJson, 0644)
	return server
}
