~jshsj/go_quiz

ref: 7f7816a2099f76fc98c4ffe1f167b7464521ca4f go_quiz/hub.go -rw-r--r-- 3.6 KiB
7f7816a2 — JSH initial commit 1 year, 8 months ago
                                                                                
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"fmt"
	"log"
	"os"
	"strings"
	"time"
)

// Hub maintains the set of active clients and broadcasts messages to the
// clients.
type Hub struct {
	// Registered clients.
	clients map[*Client]bool

	// Inbound messages from the clients.
	broadcast chan []byte

	// Register requests from the clients.
	register chan *Client

	// Unregister requests from clients.
	unregister chan *Client

	appstate ApplicationState

	timer *time.Timer

	started bool
}

const FILENAME = "./savefile"

const (
	START     = 0
	QUESTIONS = 1
	RESULT    = 2
)

const (
	GUT      = 0
	UNSICHER = 1
	SCHLECHT = 2
)

const TIMERDURATION = 5

// ApplicationState keeps the state of the app
type ApplicationState struct {
	counter int
	state   int
	results [5]int
}

func (s *ApplicationState) reset() {
	s.counter = 0
	s.state = START
	s.results = [5]int{0, 0, 0, 0, 0}
	log.Println("reset")
}

func (s *ApplicationState) addAnswer(answer int) {
	s.results[s.counter] = answer
	s.counter++

	if s.counter >= len(s.results) {
		s.state = RESULT
	}
}

func (s *ApplicationState) save() {
	log.Println("saving")
	f, err := os.OpenFile(FILENAME, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
	if err != nil {
		panic(err)
	}

	defer f.Close()
	result := strings.Trim(strings.Join(strings.Fields(fmt.Sprint(s.results)), " "), "[]") + "\n"
	if _, err = f.WriteString(result); err != nil {
		panic(err)
	}

}

func (s *ApplicationState) getResult() int {
	return 0
}

func (s *ApplicationState) asMessage() []byte {
	var message string
	switch s.state {
	case START:
		message = "Start"
	case QUESTIONS:
		message = fmt.Sprintf("Question %d", s.counter)
	case RESULT:
		message = fmt.Sprintf("Result %d", s.getResult())
		s.save()
		s.reset()
	}
	return []byte(message)
}

func newHub() *Hub {
	broadcast := make(chan []byte)
	appstate := ApplicationState{0, START, [5]int{0, 0, 0, 0, 0}}
	return &Hub{
		broadcast:  broadcast,
		register:   make(chan *Client),
		unregister: make(chan *Client),
		clients:    make(map[*Client]bool),
		appstate:   appstate,
		started:    false,
	}
}

func (h *Hub) handleMessage(message []byte) []byte {
	incoming := string(message)
	var msg []byte

	if incoming == "timeout" {
		h.appstate.reset()
		log.Print("timeout")
	} else if h.appstate.state == START {
		log.Print("start")
		h.appstate.state = QUESTIONS
	} else {
		switch incoming {
		case "gut":
			h.appstate.addAnswer(GUT)
		case "unsicher":
			h.appstate.addAnswer(UNSICHER)
		case "schlecht":
			h.appstate.addAnswer(SCHLECHT)
		default:
			break
		}
	}
	if h.appstate.state != START {
		if h.timer == nil {
			h.startTimer()
		}
		h.timer.Stop()
		h.startTimer()
	}

	msg = []byte(h.appstate.asMessage())
	return msg
}

func (h *Hub) startTimer() {
	h.timer = time.AfterFunc(TIMERDURATION*time.Second, func() {
		h.broadcast <- []byte("timeout")
	})
	//defer h.timer.Stop()
}

func (h *Hub) run() {
	for {
		select {
		case client := <-h.register:
			h.clients[client] = true
			// Send state to new clients
			client.send <- h.appstate.asMessage()
		case client := <-h.unregister:
			if _, ok := h.clients[client]; ok {
				delete(h.clients, client)
				close(client.send)
			}
		case message := <-h.broadcast:
			msg := h.handleMessage(message)
			// Send to all clients
			for client := range h.clients {
				select {
				case client.send <- msg:
				default:
					close(client.send)
					delete(h.clients, client)
				}
			}
			//Timeout

		}
	}
}

func timeout(broadcast chan []byte) {
	broadcast <- []byte("timeout")
}