draft/mlp/set.go

126 lines
2.8 KiB
Go

package mlp
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strings"
"git.fromouter.space/mcg/draft"
)
// Set is a set/expansion of MLP:CCG
type Set struct {
ID SetID
Name string
Cards []Card
}
// Card is a single MLP:CCG card in a set
type Card struct {
ID string
Name string
Subname string
Element []string
Keywords []string
Traits []string
Requirement PowerRequirement `json:",omitempty"`
Cost *int `json:",omitempty"`
Power *int `json:",omitempty"`
Type string
Text string
Rarity Rarity
ProblemBonus *int `json:",omitempty"`
ProblemOpponentPower int `json:",omitempty"`
ProblemRequirement PowerRequirement `json:",omitempty"`
}
// ToDraftCard converts cards to draft.Card
func (c Card) ToDraftCard() draft.Card {
return draft.Card{
ID: c.ID,
}
}
// PowerRequirement denotes one or more power requirements, colored or not
type PowerRequirement map[string]int
var loadedSets = make(map[SetID]*Set)
// Errors
var (
ErrSetNotLoaded = errors.New("set not loaded")
)
// CleanSetCache removes all loaded sets from memory
func CleanSetCache() {
loadedSets = make(map[SetID]*Set)
}
// LoadSetData loads sets from data
func LoadSetData(sets map[SetID][]byte) error {
for setid, setdata := range sets {
_, err := LoadSetBytes(setid, setdata)
if err != nil {
return err
}
}
return nil
}
// LoadSetMemory loads a set from memory (must have been previously loaded with LoadSetData or other functions)
func LoadSetMemory(id SetID) (*Set, error) {
// Check if set is already loaded
if set, ok := loadedSets[id]; ok {
return set, nil
}
// Not loaded, return error
return nil, ErrSetNotLoaded
}
// LoadSetBytes loads a set with a specified ID from JSON
func LoadSetBytes(id SetID, setdata []byte) (*Set, error) {
// Check if set is already loaded
if set, ok := loadedSets[id]; ok {
return set, nil
}
var set Set
err := json.Unmarshal(setdata, &set)
set.ID = id
// If set loaded fine, cache it
if err == nil {
loadedSets[set.ID] = &set
}
return &set, err
}
// LoadSetHTTP loads a set using MCG's remote server
func LoadSetHTTP(id SetID) (*Set, error) {
// Check if set is already loaded
if set, ok := loadedSets[id]; ok {
return set, nil
}
// Get SetID as string and make it lowercase
setid := strings.ToLower(string(id))
resp, err := http.Get("https://mcg.zyg.ovh/setdata/" + setid + ".json")
if err != nil || resp.StatusCode != 200 {
if err == nil {
err = fmt.Errorf("server returned non-200 response code (%d)", resp.StatusCode)
}
return nil, err
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return LoadSetBytes(id, data)
}