-
Notifications
You must be signed in to change notification settings - Fork 1
/
FileSystemStore.go
91 lines (72 loc) · 1.71 KB
/
FileSystemStore.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package poker
import (
"encoding/json"
"fmt"
"os"
"sort"
)
type FileSystemStore struct {
database *json.Encoder
league League
}
func NewFileSystemStore(database *os.File) (*FileSystemStore, error) {
database.Seek(0,0)
err := initialisePlayerDBFile(database)
if err != nil {
return nil, err
}
league, err := NewLeague(database)
if err != nil {
return nil, fmt.Errorf("problem loading player store from file %s, %v", err, database)
}
return &FileSystemStore{
database:json.NewEncoder(&tape{database}),
league:league,
}, nil
}
func FileSystemPlayerStoreFromFile(path string) (*FileSystemStore, error) {
db, err := os.OpenFile(path, os.O_RDWR| os.O_CREATE, 0666)
if err != nil {
return nil, fmt.Errorf("problem opening %s , %v", path, err)
}
store, err := NewFileSystemStore(db)
if err != nil {
return nil, fmt.Errorf("problem creating file system player store, %v ", err)
}
return store, nil
}
func (f *FileSystemStore) GetPlayerScore(name string) int {
player := f.league.Find(name)
if player != nil {
return player.Wins
}
return 0
}
func (f *FileSystemStore) RecordWin(name string) {
player := f.league.Find(name)
if player != nil {
player.Wins++
} else {
f.league = append(f.league, Player{name, 1})
}
f.database.Encode(f.league)
return
}
func (f *FileSystemStore) GetLeague() League {
sort.Slice(f.league, func(i, j int) bool {
return f.league[i].Wins > f.league[j].Wins
})
return f.league
}
func initialisePlayerDBFile(file *os.File) error {
file.Seek(0,0)
info, err := file.Stat()
if err != nil {
return fmt.Errorf("problem getting file info from file %s, %v", file.Name(), err)
}
if info.Size() == 0 {
file.Write([]byte("[]"))
file.Seek(0, 0)
}
return nil
}