From b9271e96dd0379ce5e22b0845b2e41074340440e Mon Sep 17 00:00:00 2001
From: Balthazar Wilson <wilsonba@etu.utc.fr>
Date: Fri, 20 Oct 2023 17:03:18 +0200
Subject: [PATCH] add: now possible to check results at the end of the vote

---
 agt/ballotagent/result.go | 60 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 60 insertions(+)
 create mode 100644 agt/ballotagent/result.go

diff --git a/agt/ballotagent/result.go b/agt/ballotagent/result.go
new file mode 100644
index 0000000..fae4760
--- /dev/null
+++ b/agt/ballotagent/result.go
@@ -0,0 +1,60 @@
+package ballotagent
+
+import (
+	"encoding/json"
+	"fmt"
+	"net/http"
+
+	rad "gitlab.utc.fr/gvandevi/ia04binome2a"
+)
+
+func (rsa *BallotServerAgent) sendResults(w http.ResponseWriter, r *http.Request) {
+	// mise à jour du nombre de requêtes
+	rsa.Lock()
+	defer rsa.Unlock()
+	rsa.reqCount++
+
+	// vérification de la méthode de la requête
+	if !rsa.checkMethod("POST", w, r) {
+		return
+	}
+
+	// décodage de la requête
+	req, err := decodeRequest[rad.Ballot](r)
+	if err != nil {
+		w.WriteHeader(http.StatusBadRequest)
+		fmt.Fprint(w, err.Error())
+		return
+	}
+
+	// recupération des infos
+	scrutin := req.BallotID
+	voteBallot := rad.Ballot{BallotID: scrutin}
+	ballots := make([]rad.Ballot, len(rsa.ballots))
+
+	// Check if ballot exists
+	i := 0
+	for k := range rsa.ballots {
+		ballots[i] = k
+		i++
+	}
+	if !contains[rad.Ballot](ballots, voteBallot) {
+		w.WriteHeader(http.StatusNotFound)
+		msg := fmt.Sprintf("The ballot '%s' does not exist", scrutin)
+		w.Write([]byte(msg))
+		return
+	}
+	ballot := rsa.ballots[voteBallot]
+
+	// Check que la deadline n'est pas déjà passée
+	if ballot.isOpen {
+		w.WriteHeader(http.StatusTooEarly)
+		msg := fmt.Sprintf("The ballot '%s' is not closed yet.", scrutin)
+		w.Write([]byte(msg))
+		return
+	}
+
+	w.WriteHeader(http.StatusOK)
+	serial, _ := json.Marshal(rsa.ballots[voteBallot].results)
+	w.Write(serial)
+}
-- 
GitLab